Retrieving an RSS Feed in PHP

RSS Feeds are widely used throughout the internet today and on all kinds of websites. From websites like Digg to most blogs. If you want to display an RSS feed on your website its probably easier than you think.

For this example I'm going to show you how to display the RSS feed for The Tutorial Blog using PHP.

The Code

The first two lines of code that we write are going to be what retrieve the RSS feed.

$file = file_get_contents("http://www.thetutorialblog.com/feed/");
$xml = new SimpleXMLElement($file);

Now the next thing we do is use the foreach function so for each item found do something with it
foreach($xml->channel->item as $feed){
echo $feed->title.'<br>';
}

What are code will do is simply echo the titles of all the items found within the feeds. If you also want to include a link to the feed you can do this by printing to screen $feed->link.

All the code together should look something like this.

<?php

$file = file_get_contents("http://www.thetutorialblog.com/feed/");
$xml = new SimpleXMLElement($file);

foreach($xml->channel->item as $feed){
echo $feed->title.'<br>';
}
?>

Thanks for taking the time to read this tutorial. I hope you have learned something.

Bookmark and Share
Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • email
  • FriendFeed
  • LinkedIn
  • Ping.fm
  • Tumblr
  • Twitter

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

, , , , ,

9 Responses to Retrieving an RSS Feed in PHP

  1. box August 15, 2008 at 10:12 pm #

    Simple and useful. Thanks.

  2. supersword August 19, 2008 at 7:47 pm #

    Brilliant. I have looked so hard for a good tutorial on getting contents of an RSS feed as opposed to making one!

  3. codebounce.com September 19, 2008 at 7:17 am #

    Very useful and practical tutorial..

    http://www.codebounce.com/php

  4. Unreal Media September 30, 2008 at 11:44 am #

    Great tutorial. Thanks :)

  5. Marty January 9, 2009 at 7:15 am #

    Thank you for this! So many other tutes provide far more detail than I am after.

    If I could just ask one question - how can I wrap the title in its link so people can click on it?

    Cheers

  6. Marty January 9, 2009 at 7:20 am #

    Never mind :) Thank you!

  7. Adam March 4, 2009 at 11:49 pm #

    Genius just the snip i was looking for

  8. Haris March 9, 2009 at 5:32 am #

    Cool One..!! Bt there is no Linking Function in it

  9. Vibration Plate July 19, 2009 at 10:26 am #

    Great Tutorial want to learn more about xml and php.

Leave a Reply