动态检索xml数据

I am working with simplexml to retrieve data.

The data I am having trouble with looks like this:

SimpleXMLElement Object
(
    [listing_pics_array] => SimpleXMLElement Object
        (
            [pic0] => http://imagepath.com_1.jpg
            [pic1] => http://imagepath.com_2.jpg
            [pic2] => http://imagepath.com_3.jpg
            [pic3] => http://imagepath.com_4.jpg
            [pic4] => http://imagepath.com_5.jpg
            [pic5] => http://imagepath.com_6.jpg
            [pic6] => http://imagepath.com_7.jpg
        )
)

I am able to retrieve the url like this: (string)$listing->listing_pics_array->pic0[0]

I want to dynamically loop over the listing_pic_array because I have no idea how many pics will be returned.

I want to do something like this:

foreach ($listing->listing_pics_array as $key => $value) {
    echo '<img src="'.$value .'" alt="" />';
}

but I am getting nothing returned.

Thanks.

Try casting the SimpleXMLElement into an Array. This one works fine for me:

$sXml = <<<XML
<?xml version='1.0'?>
<root>
  <listing_pics_array>
    <pic0>pic0 foo</pic0>
    <pic1>pic1 bar</pic1>
  </listing_pics_array>
</root>
XML;

$oXml = simplexml_load_string($sXml);
foreach ((array)$oXml->listing_pics_array as $sCurrentValue) {
  echo $sCurrentValue . PHP_EOL;
}

Yielded

pic0 foo
pic1 bar

HTH