Search code examples
phpxmlsimplexml

SimpleXML Parse Children With Same Name and Attributes


I can't figure out how to parse an xml file like this using simpleXML.

<root>
 <movies>
    <movie cast="some,actors" description="Nice Movie">Pacific Rim</movie>
    <movie cast="other,actors" description="Awesome Movie">Atlantic Rim</movie>
</movies>
</root>

Expected output am looking at is something like

Pacific Rim [cast="some,actors"],[description="Nice Movie"]
Atlantic Rim [cast="other,actors"],[description="Awesome Movie"]

I have tried

$xml=new SimpleXMLElement($xml_string);
foreach($xml->movies as $movie)
{
  echo $movie->cast." ".$movie->description;
}

Thanks.


Solution

  • <?php
    $xml_string = '<root>
     <movies>
        <movie cast="some,actors" description="Nice Movie">Pacific Rim</movie>
        <movie cast="other,actors" description="Awesome Movie">Atlantic Rim</movie>
    </movies>
    </root>';
    
    /* Expected result: */
    
    /* Pacific Rim [cast="some,actors"],[description="Nice Movie"] */
    /* Atlantic Rim [cast="other,actors"],[description="Awesome Movie"] */
    
    $xml = simplexml_load_string($xml_string);
    foreach($xml->movies->movie as $movie)
    {
        $name = (string) $movie;
        $attributes = $movie->attributes();
        print $name.' '.'[cast="'.$attributes['cast'].
              '"],[description="'.$attributes['description']."\"]\n";
    }
    

    In addition, you can access attributes directly with this syntax (without calling attributes()):

    print $movie["cast"] . " " . $movie["description"];