Add RSS feeds to your website

Adding a RSS feed to your website has never been this easy with PHP, especially with MagpieRSS.

magpie


About MagpieRSS
MagpieRSS is an RSS and Atom parser for PHP which supports RSS 0.9, RSS 1.0, the various Userland RSS versions (0.9x and 2.0). Additionally it supports Atom 0.3, and many custom RSS namespaces.

Features of MagpieRSS

Where to get the bird?
Download MagpieRSS from http://sourceforge.net/project/showfiles.php?group_id=55691

Sample basic script
The following script will parse the RSS feed from Slashdot and display the titles.

 
<?php
	include_once('magpierss/rss_fetch.inc');
 
	$feed = 'http://rss.slashdot.org/Slashdot/slashdot';
	$rss = fetch_rss($feed);
 
	echo '
<ul>';
	foreach ($rss->items as $item ) {
		$title = $item['title'];
		$url = $item['link'];
		echo '
<li><a href="'.$url.'">'.$title.'</a></li>
 
';
	}
	echo '</ul>
 
';
 
?>
 

First we include the rss_fetch.inc file located in the extracted magpierss folder which will help us in fetching and parsing the feed. Then we define the RSS feed URL and we tell MagpieRSS to fetch the data with the fetch_rss function. After that we just loop through the array of data and echo the output.

Note that MagpieRSS will try to create a directory named "cache" to cache the items for 1 hour to prevent excessive requests to the RSS feed. This directory must be writable by your webserver. If you want to change the cache lifespan, add

 
define('MAGPIE_CACHE_AGE', 900);
 

in your script. This will cache the items for 15 minutes (900 seconds). And if you want to change the cache directory add the following line of code :

 
define('MAGPIE_CACHE_DIR', '/tmp/feedcache');
 

The cache file will be created with a long random name and saved in the /tmp/feedcache directory

The final code looks like that :

 
<?php
	include_once('magpierss/rss_fetch.inc');
	define('MAGPIE_CACHE_DIR', '/tmp/feedcache');
	define('MAGPIE_CACHE_AGE', 900);		
 
	$feed = 'http://rss.slashdot.org/Slashdot/slashdot';
	$rss = fetch_rss($feed);
 
	echo '
<ul>';
	foreach ($rss->items as $item ) {
		$title = $item['title'];
		$url = $item['link'];
		echo '
<li><a href="'.$url.'">'.$title.'</a></li>
 
';
	}
	echo '</ul>
 
';
 
?>
 

View demo
Download demo script
MagpieRSS Homepage

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • StumbleUpon
  • Mixx
  • Ma.gnolia
  • Technorati
  • Netvouz
  • Reddit
  • Propeller
  • Slashdot
  • description

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)