Embedding RSS into a webpage using PHP

Thing #6 on Nebraska Learns 2.0 is about using a feedreader to find feeds. In keeping with trying to learn something new, I decided to learn how to embed RSS into a web page for Thing #6. Turns out this is pretty easy.

There is an extremely easy way to do this: You can use Feed2JS Build JavaScript tool to embed an RSS feed on your website. But I wanted to learn how to do this naively, and, since I am trying to learn PHP, I wanted to learn to do it using PHP.

Why naively?

Well, I don’t like depending on an external site (beyond the RSS feed, of course) to display the content- it’s just one more thing that can break. If all the code resides on my own server, it will be up when my site is up. You can Download Feed2JS and host on your own server as well.

There are, as it turns out, lots of ways to do this, and as with most things I am learning, someone has already done all the hard work.

All I had to do was search for “rss php” and the very first thing that came up was a nice set of php scripts called Magpie RSS. Download the package, extract (I use portable 7-Zip for this) and copy these files to a new directory:

  • folder: extlib
  • rss_cache.inc
  • rss_fetch.inc
  • rss_parse.inc
  • rss_utils.inc

Then you need a php page in that same directory with something like the following code:

<?php
require_once('rss_fetch.inc');

$url = 'http://l2ne.blogspot.com/feeds/posts/default?alt=rss';
$rss = fetch_rss($url);

echo "Site: ", $rss->channel['title'], "<br>\n";
foreach ($rss->items as $item ) {
	$title = $item[title];
	$url   = $item[link];
	echo "<a href=$url>$title</a></li><br>\n";
}
?>

This will work as long as your php page is in the same directory as the scripts. If you want to store the scripts in another place on the server, you have to alter the first line slightly:

define('MAGPIE_DIR', '/path/to/your/directory/');
require_once(MAGPIE_DIR.'rss_fetch.inc');

And, of course, you have to change the URL to the RSS feed you want to display. There are lots of other options- the download comes with some sample files to play with. It’s easier than I thought it would be. :)

This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

One Response to Embedding RSS into a webpage using PHP

  1. alan says:

    thankyou a heep