tags:

views:

242

answers:

4

Hello there,

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?

A: 

Try 'rss/channel/item.' (with dot)

powtac
Hi Powtac,The dot returns no results... Where is it for anyway? ^^
Harmen
A: 

The xpath function returns an array of elements matching the path. So that's why you get the outer array with one element. You don't want to use xpath to get the title. You want to get the title attribute from the element. Just access it directly.

Jeremy Stein
A: 

Try:

$item->xpath('string(title)')
Pavel Minaev
A: 

Try:

foreach($xml->xpath('/rss/channel/item') as $item)
{
    print_r($item->title); // This pulls out the simpleXML object
    print_r((string)$item->title); // This pulls out the string as expected
}

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.

null