doutian4046 2016-05-03 15:12
浏览 28
已采纳

如何在PHP中使用SimpleXML列出数组的特定部分?

So I have this XML file and I need to list only sites specific to each region.

<xls2cli>
   <Region id="Region1">
      <site>Site1</site>
      <site>Site2</site>
   </Region>
   <Region id="Region2">
      <site>Site3</site>
      <site>Site4</site>
      <site>Site5</site>
      <site>Site6</site>
   </Region>
   <Region id="Region3">
      <site>Site 7</site>
   </Region>
</xls2cli>

I am able to list all the sites but no matter what I try, I cant get it to list only sites specific to each region. Im looking to do it a way where I can have something like Region['Region1']->site but obviously that doesnt work. Is there way to do this without using indexes?

foreach ($xls2cli->Region as $Region){
            echo $Region[id]."<br>";
                foreach ($Region->site as $site){
                    echo $site."<br>"; }    }
</div>
  • 写回答

1条回答 默认 最新

  • doujing2017 2016-05-04 09:45
    关注

    SimpleXML doesn't know that id is anything special, it's just part of the data. The simplest approach is just a boring old if statement in your existing loop:

    foreach ($xls2cli->Region as $Region){
        if( $Region['id'] == 'Region1' ) {
            echo $Region['id']."<br>";
            foreach ($Region->site as $site){
               echo $site."<br>"; 
            }
        }
    }
    

    You can also use the xpath() method, which can do queries based on the content of the XML:

    foreach ( $xls2cli->xpath('./Region[@id="Region1"]') as $Region ) {
        echo $Region['id']."<br>";
        foreach ($Region->site as $site){
            echo $site."<br>"; 
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line