Grab RSS feed with PHP

I would like to share a PHP function for writing out parts of an RSS feed to a page. I used this in the redesign of ryanbosinger.com to show the latest three posts of this blog.

To use it, just call the function where you’d like it show up like so:

<?php getFeed("http://ryanbosinger.com/blog/feed", 3); ?>

The second parameter is the amount of posts to show. It will write out as an unordered list. You can choose to write out different parts of the feed by changing: $x->channel->item[$i]->[name-of-feed-tag]

<?php
function getFeed($feed_url, $posts_to_show) {
 
	try 
	{
		$content = file_get_contents($feed_url);
		$x = new SimpleXmlElement($content);
 
		echo "<ul>";
 
		$i = 0;
 
		while ($i < $posts_to_show){
			echo "<li><a href=\"" . $x->channel->item[$i]->link . "\" title=\"" . $x->channel->item[$i]->title . "\" target=\"_blank\">" . $x->channel->item[$i]->title . "</a></li>";
			$i++;
		}
 
		echo "</ul>";
 
	} 
	catch (Exception $e) 
	{
		echo "<p>The blog feed doesn't seem to be available at the moment...</p>";
	}
}
?>

9 Comments »

  1. This is brilliant, I have been scouring the net for this exact code. Going to use it on my website with some slight modifications. Thanks so much!

    Comment by Josh — February 20, 2010 @ 2:44 am

  2. Excellent. Thank you very much!

    Comment by caoson148 — February 23, 2010 @ 3:45 am

  3. Hey -Thanks heaps for this!

    One thing though – Is it possible to offset the number of posts i.e. skip over the 4 most recent posts and grab from there onwards?

    I’m a total beginner so have tried a few things but I’m beginning to go around in circles…

    Thanks again!

    Comment by Simon Every — October 6, 2010 @ 8:53 pm

  4. Simon,

    Try changing the line

    echo “channel->item[$i]->link . “\” title=\”" . $x->channel->item[$i]->title . “\” target=\”_blank\”>” . $x->channel->item[$i]->title . ““;

    to

    if (i>3) { echo “channel->item[$i]->link . “\” title=\”" . $x->channel->item[$i]->title . “\” target=\”_blank\”>” . $x->channel->item[$i]->title . ““; }

    You can change the number in (i>3) to anything you wish…

    Comment by Paul — October 25, 2010 @ 11:38 am

  5. THANK YOU. I’ve been looking for an RSS title fetcher for a really long time now.

    Comment by Apolyonn — January 9, 2011 @ 4:03 pm

  6. Holy smokes this is great. Thanks Ryan!

    Comment by Rich Malloy — July 25, 2011 @ 10:35 am

  7. please contact me at 604 835 0036 found your wallet outside my jobsite on west 1st avenue

    Comment by hank krahn — December 31, 2011 @ 4:13 am

  8. thanks a lot! It saved my time its easily understandable

    Comment by anand — March 15, 2012 @ 3:49 pm

  9. *Bow*

    Comment by Thanks to You — March 25, 2012 @ 7:30 pm

Leave a comment