dongzongzi0379 2013-06-19 22: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 22: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.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?