Search code examples
phpxmlsimplexml

Looping through simplexml_load_file results


I'm trying to use simplexml_load_file to get the info in my xml file into variables. The structure of the xml file is:

<root>
    <item>
        <sku></sku>
        <weight></weight>
        <Price></Price>
        <media>
            <images></images>
            <images></images>
            <images></images>
        </media>
        <short_description>
            <![CDATA[]]>
        </short_description>
        <description>
            <![CDATA[]]>
        </description>
    </item>
    <item>
        <sku></sku>
        <weight></weight>
        <Price></Price>
        <media>
            <images></images>
            <images></images>
            <images></images>
        </media>
        <short_description>
            <![CDATA[]]>
        </short_description>
        <description>
            <![CDATA[]]>
        </description>
    </item>
</root>

Here's what I've done so far, but it's only getting the first image for each item not all the images. Apart from that it seems to be working fine.

$xml_url="accessories.xml";
$xml = simplexml_load_file($xml_url);
foreach($xml->item as $_item){
    echo $_item->sku . " - ";
    echo $_item->weight . " - ";
    echo $_item->Price . " <br/>";
    //echo $_item->short_description . " <br/><br/>";
    foreach($_item->media as $_media){
        echo $_media->images . "<br/>";
    }
}

My php and xml skills are pretty limited so I'd appreciate any help you can give.
Thanks


Solution

  • You should use like following foreach

    foreach($_item->media->images as $_media){
        echo $_media . "<br/>";
    }
    

    You'll see because of why with below dumped media data:

    var_dump($_item->media);
    
    object(SimpleXMLElement)[5]
      public 'images' => 
        array (size=3)
          0 => string '1' (length=1)
          1 => string '2' (length=1)
          2 => string '3' (length=1)