开发者

Can SimpleXML load only a partial of a XML?

Is there a way not to load the whole feed bu开发者_Python百科t only the first 10 <item></item> tag?

$feed = 'rss file';
$xml = simplexml_load_file($feed); //not the entire feed though


No. A DOM parser (such as SimpleXML) can only load 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;
}


With use of the XMLReader you can achieve this. This avoids the consumption of 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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜