Getting RSS data is really simple…

Posted Oct 25th, 2008 by David Calhoun in rss, xml

As its name suggests, RSS (Really Simple Syndication) turns out to be just that - quite easy.  RSS is basically a simple XML feed, and as I have limited experience with XML, it’s always been a mystery to me how exactly you go about receiving and manipulating that data.

As it turns out, in PHP 5 it’s even easier than before.  We can essentially get RSS data (or any XML data, for that matter) with two lines of code, using functions that come with PHP by default:

$xml_string = file_get_contents('http://rss.cnn.com/rss/cnn_topstories.rss');
$xml_object = new SimpleXMLElement($xml_string);

And voila!  We now have the entire contents of the Top Stories RSS feed from CNN, all contained in $xml_object.

If we want to get the title of the top 2 stories, we simply do this:

$title1 = $rss->channel[0]->item[0]->title;
$title2 = $rss->channel[0]->item[1]->title;

The same can be done with the link and description fields, as in this example, where we grab a couple pieces of data to show information related to the top story:

$top_story = $rss->channel[0]->item[0];
$title = $top_story->title;
$link  = $top_story->link;
$description = $top_story->description;
echo <<< HTML
Top story on CNN:<br>
<a href="$link">$title</a><br>
$description<br>
HTML;

Then we have something that looks like this:

Notice that CNN puts some extra links at the bottom of the story description.

All this turns out to be ridiculously powerful, and I’m surprised I didn’t learn this sooner!

Download the Code

Download the code and example.  <- the above code put into a function called xml_to_object, with error handling and all.

  • Jasmine Turner on 20 May 2010 at 12:55 pm

    RSS Feeds are really very helpful and you could get site and news updates from it.*`*

  • Amy Morris on 28 Jul 2010 at 2:42 am

    RSS feeds are really great because you are always updated with the latest news or blog posts.;*’

Trackback URI | Comments RSS

Leave a Reply

Categories