[SimplePie] Merging RSS Feeds With SimplePie PHP RSS and Atom parser

Tags: | | |

SimplePie is a very fast and easy-to-use PHP class that has made web developers lives very easy as far as RSS and Atom feeds parsing is concerned. Not just parsing, but SimplePie can also merge different RSS feeds very efficiently to put it on your web page.

In addition to merging and sorting multiple feeds by date, SimplePie allows you to cache the parsed output and can also parse enclosure tag and display image if available for that item.

Let’s see how you can do all of this:

 
//path to simplepie class
require_once('/simplepie.inc');
 
//first of all, define few feeds to fetch and merge
$feed1_url = 'http://www.parorrey.com/blog/feed/';
$feed2_url = 'http://blogs.sitepoint.com/feed/';
$feed3_url = 'http://feeds.bbci.co.uk/news/rss.xml?edition=int';
 
$feed = new SimplePie(); // bake a new pie
$feed->set_feed_url(array( $feed1_url, $feed2_url, $feed3_url));  // specify feed urls to merge
$feed->set_cache_duration (3600); // specify cache duration in seconds
$feed->handle_content_type(); // text/html utf-8 character encoding
$check = $feed->init(); // script initialization check
 
 if ($check){
 
 foreach ($feed->get_items() as $item) {	 
 
if ($enclosure = $item->get_enclosure()) $thumb = '<img src="'.$enclosure->get_link().'" alt="'.$item->get_title().'" width="250"/>';
 
	 else $thumb = ''; //if image not available, set it to blank
 
$merged_rss_feeds .= '<div class="rssItem"><span class="date">'.$item->get_date('j F Y @ g:i a').'</span>
 
		<h3><a href="'.$item->get_permalink().'" title="'.$item->get_title().'" target="_blank" rel="no-follow">'.$item->get_title().'<br/>'.$thumb.'</a></h3>		
 
    <p>'.$item->get_description().'</p></div>';
 
 }
 
}
 
 
echo '<div id="rssNews">
 
 '.$merged_rss_feeds.'
 
</div><!--end#rssNews-->';

All you have to do is to provide the path to simplepie.inc file and define feed urls to merge and you are away.

Please note that merged feed is sorted by date but if you don’t see the output that way, make sure you are not trying to merge in one or more feeds where the items’ date stamps are missing.

Hope that helps.

Cheers!

Related posts:

  1. How to fetch, parse, cache, and display your external RSS and Atom feeds and mediaRSS on your website using SimplePie
  2. Use WordPress Different Category RSS Feeds for Search Engine Optimization
  3. Setting different cache age for different feeds using Magpie RSS – PHP RSS Parser
  4. Parsing News Feed using PHP & MagpieRSS and making it scroll
  5. [MySQL] Setting date data type default value NULL instead of 0000-00-00