Can SimpleXML load only part of XML?

Is there a way not to download the entire feed, but only the first <item></item> ?

 $feed = 'rss file'; $xml = simplexml_load_file($feed); //not the entire feed though 
+4
source share
2 answers

No. A DOM parser (such as SimpleXML) can load only the entire document.

But you can use XPath to filter the relevant parts:

 $xml = simplexml_load_file($feed); $top10 = $xml->xpath('/rss/channel/item[position() <= 10]'); foreach($top10 as $item) { // output $item; } 
+4
source

With XMLReader, you can achieve this. This avoids a large amount of RAM.

 $xmlr = new XMLReader(); $xmlr->open('path/to/file'); // ... // move the pointer with $xmlr->read(), $xmlr->next(), etc. to the required // elements and read them with simplexml_load_string($xmlr->readOuterXML()), etc. // ... $xmlr->close(); 
+2
source

All Articles