开发者

xml problem with php

I'm trying to use an xml file and retrieve all links from it. so far I have:

$xmlHeadline = $xml->channel[0]->item[3]->link;
print($xmlHeadline);

This works ok to print the single headline link for item[3] in the xml. But as you can see it is 2 levels deep. Then next one will be at channel[0]->开发者_如何学Go;item[4]->link. There is no channel 1, just channel[0].

All the examples on the internet only deal with 1 level deep. They all used a foreach loop, but I am not sure if that can be used here...

How can I cycle through all item's in the xml and echo all links?


Try

foreach ($xml->channel[0]->item as $item) {
    echo $item->link;
}

or

foreach ($xml->xpath('/channel/item/link') as $link) {
    echo $link;
}


I think you want a DOM parser, that will allow you to load the xml as a structured hierarchy and then use a function like getElementById http://php.net/manual/en/domdocument.getelementbyid.php to parse the xml and get the specific items you want at any depth.

If you provide the structure of the xml file I may be able to help with the specific use of a DOM function.


$str = '<channels><channel>
<item><link>google.com</link></item>
<item><link>google.com.cn</link></item>
<item><link>google.com.sg</link></item>
<item><link>google.com.my</link></item>
</channel></channels>';
$xml  = simplexml_load_string($str);
$objs = $xml->xpath('//channel/item/link');

PS: Please include some example of your xml

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜