Analyzing remote xml in php using simpleXML

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 the "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 expected the script to echo "desc1desc2", but nothing will happen again.

* UPDATE

Here is the full code (I am reading 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; } 
+4
source share
2 answers

SimpleXML is not an easy task, you need to explicitly specify everything

echo (string)$item->description;

must work.

EDIT: also, what about the "inner text"? Cut it out. And one more thing in this XML is the content enclosed in some root node, for example <items> ? If not, foreach will not work.

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

 foreach ($xml->channel->item as $item) { echo (string)$item->description; } 
+3
source

I believe this will work:

 echo $item->description 

Exit from the internal context.

0
source

Source: https://habr.com/ru/post/1402684/


All Articles