4

I have the following xml

<rss>
<channel>   
<item><title><![CDATA[bla]]></title><description><![CDATA[desc1]]></description><link>blah</link></item>
<item><title><![CDATA[bleh]]></title><description><![CDATA[desc2]]></description><link>blahhh</link></item>
</rss>
</channel>  

I want to get all the text in "description" however it is surrounded by CDATA.I thought the following would work

$xmlurl = file_get_contents('http://anxmlfile.xml');    
$xml = simplexml_load_string($xmlurl, null, LIBXML_NOCDATA);

foreach ($xml->item as $item) {
   echo $item->description->innertext;
}

I was expecting the scrript to echo "desc1desc2", however nothing is ever echo'd.

*UPDATE

Here is some full code (I am making an rss reader)

$xml = new SimpleXMLElement('http://www.skysports.com/rss/0,20514,11661,00.xml', LIBXML_NOCDATA, true);


/* For each <character> node, we echo a separate <name>. */
foreach ($xml->item as $item) {
   echo (string)$item->description;
}
2
  • Just a minor improvement: The loading of the xml can be achieved using $xml = new SimpleXMLElement('http://anxmlfile.xml', LIBXML_NOCDATA, true); Commented Mar 21, 2012 at 15:51
  • Thank you I have adjusted my code to include this Commented Mar 21, 2012 at 15:57

2 Answers 2

3

SimpleXML is kind of tricky, you need to explicitly typecast everything,

echo (string)$item->description;

should work.

EDIT: also, what's with the "innertext"? Cut that out. And another thing, in that XML, is the content wrapped in some root node, such as <items>? If not, foreach won't work.

EDIT2: okay, after the edited question, it becomes clearer, you're doing the iteration wrong, leaving out <channel>. This will work:

foreach ($xml->channel->item as $item) {
   echo (string)$item->description;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi cypher, there is a root node "rss" and the parent node of item is "channel". I have edited my post with a replicatable piece of code
I love you and I want to have your babies.
0

I believe this would work:

echo $item->description

Leaving the innertext out.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.