• Skip to content
  • Skip to primary sidebar

The html blog

The web sandbox

You are here: Home / php / Add RSS feeds to your website

Add RSS feeds to your website

September 29, 2017 By thehtmlblog Leave a Comment

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

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

  • Easy to Use
  • Parses RSS 0.9 – RSS 1.0
  • Integrated Object Cache
  • HTTP Conditional GETs
  • Configurable
  • Modular
  • Secure
  • Bandwidth friendly

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.

	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 :

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

Filed Under: php Tagged With: magpie rss, news, parse, PHP, rss, slashdot, Tags feed, xml

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Subscribe and never miss a post

Categories

  • Hosting
  • Javascript
  • php
  • Web
  • XML

Copyright © 2021 · htmlblog.net