Search code examples
phprsssimplexml

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

Solution

  • // 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.