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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog