php – 使用SimpleXML解析多个RSS源

如何将SimpleXML中的多个RSS源放入按pubDate排序的数组中?

例:

feed[0] = 'http://www.example.org/feed1.rss';
feed[1] = 'http://www.thing.org/feed.rss';
...
feed[n] = '..';

#Fetch feeds
#Sort by pubDate

foreach ($feeds as $row) {
   //Do something
   print '<item>
          <title>...</title>
          </item>';
}

解决方法:

// Set the feed URLs here
$feeds = array(
    'http://www.example.org/feed1.rss',
    'http://www.example.org/feed2.rss',
    // etc.
);

// Get all feed entries
$entries = array();
foreach ($feeds as $feed) {
    $xml = simplexml_load_file($feed);
    $entries = array_merge($entries, $xml->xpath('/rss//item'));
}

// Sort feed entries by pubDate (ascending)
usort($entries, function ($x, $y) {
    return strtotime($x->pubDate) - strtotime($y->pubDate);
});

print_r($entries);

适用于PHP 5.3.

上一篇:php – 哪种编码HTML的RSS更好?


下一篇:php – 使用Zend Layout时添加RSS自动检测