dongzongzi0379 2013-06-19 14:22
浏览 31
已采纳

PHP RSS提要阅读器效率

I'm reading data from an XML feed as follows:

$data=file_get_contents("mydata.rss");

$data=simplexml_load_string($data);

foreach($data->channel->item as $item){ 

     $articles[] = array(
                    'description' => (string)$item->description,
                    'link' => (string)$item->link,
                    'pubDate' => (string)$item->pubDate,);

} 

The issue is that the feed is very long with maybe 100 items. I only want read the first 10. I can work around this by manually setting a counter and then using an if statement within the foreach loop but I don't think that is the best approach as the entire feed is still be read and therefore unecessary overhead is added.

what's the most efficient way of achieving this without reading the entire feed?

Thanks in advance...

  • 写回答

1条回答 默认 最新

  • doubushi0031 2013-06-19 14:56
    关注

    Using SimpleXML, as you say, you load all the file in memory and then it's parsed. Then you iterate over the loaded elements in memory.

    Using a SAX-like parser like "XML Parser", will allow you don't read the full file. I don't know how exactly is implemented, but the aproach in SAX is fire an event every time a new element is detected. Then, you can start reading the RSS and stop parsing when the 10th element of type "item" is closed.

    This aproach has smaller memory footprint and is faster. In the other hand, it's not as easy iterate over the elements of the XML.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部