Search code examples
phphtmlsimplexml

How to list specific part of array using SimpleXML in PHP?


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>"; }    }

Solution

  • 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>"; 
        }
    }