使用SimpleXML解析多个RSS源

时间:2011-01-18 00:57:12

标签: php rss simplexml

如何将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>';
}

2 个答案:

答案 0 :(得分:7)

// 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。

答案 1 :(得分:0)

您将项目值放入多维数组,然后使用usort()排序,然后打印。你有更具体的问题吗?