I’m trying to print all the <title> and <description> elements of an RSS 2.0 feed in a list using PHP. I could simply get these elements using: $rss->xpath('rss/channel/item/title | rss/channel/item/description') but I want to use it a little different.
I want to use PHP to iterate through all the <item> elements using a foreach statement like this:
<?php
foreach($xml->xpath('/rss/channel/item') as $item){
print_r($item->xpath('title'));
}
?>
But $item->xpath('title') does not return the text inside the title element, but it returns an array:
Array
(
[0] => SimpleXMLElement Object
(
[0] => Ubuntu 10.04 LTS 'Lucid Lynx' laat Gnome 3 nog links liggen
)
)
Why does it return an array and not the text inside the element?
Try:
There is no need to use another XPath query when using SimpleXML, the first XPath will pull out an array of simpleXML object matching the XPath. Then all you need to do is access the node as if it were a property of the SimpleXML object. If you would like it to be used as a string then you need to cast it to one by placing the
(string)in-front of the property.