ensnare
ensnare

Reputation: 42013

Use SimpleXML to parse multiple RSS feeds

How can I put multiple RSS feeds from SimpleXML into an array sorted by pubDate?

Example:

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>';
}

Upvotes: 4

Views: 4440

Answers (2)

scoffey
scoffey

Reputation: 4688

// 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);

Works in PHP 5.3.

Upvotes: 7

dqhendricks
dqhendricks

Reputation: 19251

You put the item values into a multi-dimensional array, then sort using usort(), then print. Do you have more specific questions?

Upvotes: 0

Related Questions