Consuming RSS Feeds
videos

How to Read an RSS Feed With PHP – screencast

Back in April, Collis Ta’eed – CEO of Envato – wrote a fantastic tutorial on designing a tab structure using CSS/HTML/JS.

If you haven’t already, I 100% recommend that you review it. However, dynamically pulling in an RSS feed was beyond the scope of that article. In today’s video tutorial, I’ll show you exactly how to do this using PHP. At roughly forty-five minutes in length, you might want to take a quick “pre-screencast bathroom break”. You also might want to grab some raisins.

There’s a strange issue with converting this video to Flash. At least for the next couple of hours, you can watch the video HERE. I’ll embed the video on this site shortly.

Our Goal

We’ll be creating a tab system for three unique RSS feeds:

We want to dynamically import these feeds into our document. Our server-side script of choice today will be PHP, and we’ll use some jQuery to create the tab structure.

*Note – the intention of this tutorial is to demonstrate the back-end work involved. As mentioned previously, Collis has already created a wonderful skin. Just as the programming was beyond the scope of that tutorial, working on “design” will be beyond the scope of this article. To keep things as clean and “to the point” as possible, we’ll be using the most naked form of a tab structure – speaking in terms of the design.

Collis’s final product.

Collis

Our naked skin

Tab Final

Step 1: Creating the File Structure

Open your favorite code editor and create the following folders/files. The PHP files can be blank for now.

File Structure

Step 2: The Logic

Open your “functions.php” file. We’ll be creating only one function that’s relatively simple. First, copy in the following code. After that, continue reading for the code analysis.

<?php

function getFeed($feed_url) {
	
	$content = file_get_contents($feed_url);
	$x = new SimpleXmlElement($content);
	
	echo "<ul>";
	
	foreach($x->channel->item as $entry) {
		echo "<li><a href='$entry->link' title='$entry->title'>" . $entry->title . "</a></li>";
	}
	echo "</ul>";
}
?>

First, we’re creating a function called getFeed(). The basic structure of any PHP function is:

function someName($parameters) {
...some method
}

Next, we’re creating a variable called “$content” and making it equal to the result of: file_get_contents($feed_url).

“file_get_contents” is the preferred way to read the contents of a file into a string.”

Now that you understand the definition, we only need to pass in our file. We have two choices. First, we could pass in a string to our RSS feed – like so:

file_get_contents("http://feedproxy.google.com/nettuts");

That would work just fine, I suppose. The method would correctly read the RSS feed and store the results in our “$content” variable. But, we should always have the word “reusability” lurking in the back of our minds when working.

Imagine that we have many different pages in our web application that want to call this “getFeed()” function. But, what if they want to grab different feeds? Wouldn’t it be nice if we could pass the url into the function instead of hard-coding it? Of course it would! Consequently, rather than inputting the path, we’ll simply use a variable called “$feed_url”.

file_get_contents($feed_url);

In order to use this variable from an outside source, we need to make sure that the function accepts one parameter.

function getFeed($feed_url){

}

Now, when we call the function, we can do so like this:

<?php getFeed("path to some RSS feed"); ?>

Next, we’ll create a new instance ($x) of SimpleXmlElement. Within the parenthesis, we’ll pass in our $content variable.

$x = new SimpleXmlElement($content);

Finally, we need to run through the RSS feed and extract the information that we desire.

	echo "<ul>";
	
	foreach($x->channel->item as $entry) {
		echo "<li><a href='$entry->link' title='$entry->title'>" . $entry->title . "</a></li>";
	}
	echo "</ul>";

We begin by echoing the opening unordered list tag. Then, we cycle through each entry in our RSS feed using a “foreach” statement. This statement basically says, “create a variable called $entry that will contain the value of each item tag in our RSS feed.

The wonderful thing about RSS feeds is that they all implement the same basic structure. Every feed contains a wrapping “channel” tag. Then, each posting in your feed will be wrapped within an “item” tag. All of the information that we need can be accessed this way.

RSS Info

Within our “foreach” statement, we only need to extract the link and title, and place it within an “li” tag. The “link” tag contains a link to the actual posting. The title tag obviously houses the title of the posting. That’s all that we’ll need for this particular project, but I’d advise you to review some of the other information that is available to you. Simply view the source of any RSS feed to analyze the structure.

Our logic is now complete. We now need to create our index.php page and call the function.

Step 3: The Index.php Page

Paste the following code into your index.php page.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
	<link rel="stylesheet" href="css/default.css" />
	<script src="js/jquery-1.2.6.pack.js" type="text/javascript"></script>
	<script src="js/myScript.js" type="text/javascript"></script>
</head>
<body>
<?php require_once "includes/functions.php"; ?>
<div id="wrap">

<ul id="nav">
<li><a href="#content_1" class="selected">NETTUTS</a></li>

<li><a href="#content_2">ThemeForest</a></li>
<li><a href="#content_3">Screencasts</a></li>
</ul>

	<div id="mainContent">

		<div id="content_1">
			<?php getFeed("http://feedproxy.google.com/nettuts"); ?>
		</div><!--end content 1-->

		<div id="content_2">
			<?php getFeed("http://feedproxy.google.com/themeforest"); ?>
		</div><!--end content 2-->

		<div id="content_3">
			<?php getFeed("http://feeds.feedburner.com/NETTUTSVideos"); ?>
		</div><!--end content 3-->

	</div><!--end main content -->

</div><!--end wrap-->
</body>
</html>

As I said earlier, I don’t want to go too much into the “design”. Collis has already done that for you. Refer to that tutorial for your “design fix”. But for a speedy overview, we’re storing our navigation links within an unordered list that has an id of “nav”. In our main content section, we have three divs named “content_1″, “content_2″, and “content_3″, respectively. Inside each division is where we call our “getFeed” function – and pass in the different urls to our RSS feeds.

Add in some extremely basic CSS and you get this:

what we have now

Implementing the Tabs With jQuery

jQuery Website

Open your “myScripts.js” file and paste in the following code:

$(function() {
    $('#mainContent div:not(:first)').hide();

    $('ul li a').click(function() {
        $('ul#nav li a').removeClass('selected');
        $(this).addClass('selected');

        var href = $(this).attr('href');
        var split = href.split('#');

        $('#mainContent div').hide();
        $('#mainContent div#' + split[1]).fadeIn();

        return false;
    });
});

When the document is ready to be manipulated, we’ll grab all of our content divs – but not the very first one – and hide them. This will remove the second two RSS feeds.

Next, when a user clicks on one of our navigation links, we’ll run a function. Inside this function, we’ll remove the class “selected” from all of our navigation anchor tags. This class is used to provide some visual feedback as to which tab is currently selected. In this naked example, I’ve simply made the text bold for that particular tab. Now we add this class specifically to the anchor tag that was clicked – $(this).addClass(‘selected’);

Moving along, we’re creating a variable called ‘href’ and are making it equal to the href of the anchor tag that was clicked. If we refer back to our document, these navigation tags link to the sections within the main content – “#content_1″, “#content_2″, “#content_3″. The idea is that, if the user doesn’t have Javascript enabled, these links will scroll the user directly to the proper feed.

This additionally serves another unique advantage. Consider this: the NETTUTS navigation tag has its url set to “#content_1“. Now, in the main content section, the div with an id of “content_1” houses our NETTUTS RSS feed. So…we have made a connection between the two! I hope that makes sense; it’s a little hard to describe. Refer to the screencast if I didn’t illustrate this point well enough.

I’m going to use “split” to strip off the # sign. Split works in the same way as PHP’s explode function does.

var split = href.split('#');

Now, the “split[1]” array will be equal to “content_1″. The final step is to find the main content div that has that exact id and fade it in accordingly.

$('#mainContent div#' + split[1]).fadeIn();

I hope this tutorial has helped you. Once you combine the design from Collis’s tutorial with the logic from this one, you’ll find yourself with a fantastic addition to your sidebar. Though, this tut should serve as the first step for beginners. I welcome all of you to refine the code to make it more advanced and error proof. I didn’t go into the latter part in order to save something for Part 2! :p

  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.


Tags: Videos
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://themeforest.net/user/JeffreyWay Jeffrey Way
    Author

    @Sean – You could add an “i” variable and do something like…

    $i = 0;
    while (bla bla) {
    pull individual article code
    $i++;
    if ($i == 5) break;
    }

    • Antony

      First of all thank you very much such a great tutorial, i tried it working well. I am very new to php and trying to limit the rss feeds coming in to 5, you given a nice hint here but i am not able to make out. should i alter the code in the functions? I am totally stuck here. i am looking out some more help here………

  • http://www.themolitor.com THEMOLITOR

    Thanks Jeffrey!

  • http://www.themolitor.com THEMOLITOR

    I may have spoken too soon…I made the change, but now the tabs don’t switch between the different content when clicked???

  • PHPLONDON

    The Video On Blip.tv doesn’t work???????? I’ve tried several times!! Jeff can you please embed the Video asap so i can watch it??

    Just found out about this site on a forum WOW! keep up the good work. This is now my most favourite site ;-)

    PHPLONDON

  • Chris Geo

    when doing something similar for my site a year ago i used cron jobs to run the fetch rss script which grabbed the rss content from multiple sites every 15 mins and stored them in a xml file. I then included the xml file content in the html page which I was supposed to saved loads in bandwidth and page load time only running the script once every 15 rather then ever page view. Seems to me this method shown in the video will make requests across the web on every page view so if you have a high traffic site your server will get rapped. Am I wrong?

  • Pingback: 30+ Eye-Opening Web Development Screencasts - NETTUTS

  • http://sarmenhb@yahoo.com sarm

    for those of your wondering why it doesnt work that is because he hasnt told us what class file to include. how on earth are we supposed to know?

  • http://www.script2please.com indrajit

    it helped me to use other tools, flash wizards

  • http://blog.kudson.com/webbaba/ NinNin

    Work well but not with feedburner url.

  • http://www.goaltalk.net Dodant

    I got everything to work except when I choose a link, it doesn’t display. It clears the screen of everything but the tabs. (this is with your downloaded code)

    When I try your demo, it seems to work fine.
    Ideas?

  • http://www.goaltalk.net Dodant

    Fixed!!!!
    I read the comments and my problem was already listed.

    So changed the line to:

    $(’ul#nav li a’).click(function()….

  • http://gheymatha.com فارکس

    thanks , it helped me parsing rss with php

  • Pingback: How to Read an RSS Feed With PHP - screencast - Nettuts+

  • http://www.linxiting.com Wim

    Great tut, but…
    I have a problem with getting rss-feeds with php. Everything goes great, but when I go to my website (http://www.linxiting.com) you will see that it takes about 7 seconds to load it. I’m allready using magpierss to cache the feeds and then load them from the cache-file, but every 1 hour I have the same problem again and again (timer of my cache is set at 1 hour and I can’t increase that). Does anyone has a solution for this problem, so the rss-feeds will load almost immediatly??

    Please help!

    Many thanks!

  • Bryan

    Hi

    Great tutorial
    I got a problem i’m getting this error on my page where the feed should ‘Invalid argument supplied for foreach()’

    Can any one Help

  • Joe

    Hi, I am getting this:

    Fatal error: Cannot instantiate non-existent class: simplexmlelement in /home/website_name/public_html/includes/functions.php on line 7

    I used phpinfo() and allow_url_fopen is set to On.

    I make a terrible PHP programmer =p. Can anyone give an example of a fix? Someone mentioned using curl or making sure simpleXml is loaded.

    I was trying to use w3schools ajax-rss feed tutorial and that failed giving me
    Parse error: syntax error, unexpected T_OBJECT_OPERATOR in /home/website_name/public_html/getrss.php on line 21. I know my server says it is running PHP 5.2.9

    Any PHP ninja/pirates that can hack and slash this? Thanks!

    • Les

      Sort it out yourself mate, if you want to call yourself a programmer.

      That is what programming is all about – learning to solve your own problems, it’s not about using scripts in the wild and running off to your mummy when you stump your toe.

      If you can’t solve this simple error on your own, then how on earth do you expect to make it in the real world?

      Someone give him a hanky, please…

  • Les

    Wow… Cool tutorial?!

    Please… Lets see you do it without SimpleXml… Lets see you do it how real programmers do it and that is with the DOM.

    SimpleXml is for… well, simple people really, but to use the DOM takes more brain power – do you have that?! ;)

  • http://aext.net Lam Nguyen

    Thanks, this tuts is great!

  • Steve

    great tut!

  • art.mania

    hey working cool. thanks!! but i have an issue about chars :S

    for example –> He’s going…

    show like –> He’s going…

    why is this problem? how can i fix? :/

  • Pingback: The Right Way To Build WordPress As A Community News | AEXT.NET

  • http://vietnam.vn caoson148

    -Question: How do you limit the amount of feeds coming in?
    -Reply:
    + index.php:

    + include/functions.php:

    <?php
    function getFeed($feed_url, $posts_to_show) {

    try
    {
    $content = file_get_contents($feed_url);
    $x = new SimpleXmlElement($content);

    echo "”;

    $i = 0;

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

    echo “”;

    }
    catch (Exception $e)
    {
    echo “The blog feed doesn’t seem to be available at the moment…”;
    }
    }
    ?>

  • http://www.heroes-villains.com Alexis

    Awesome demo! didn’t even know about the PHP SimpleXmlElement I always used DOMX. Nice jquery to.
    Just been helping my brother get this going another site. And notice the down-loadable ZIP isn’t quite up to date.

    In the download line 4 of myScript.js file is
    $(‘ul li a’).click(function() {
    and needs to be the same as the live demo with
    $(‘ul#nav li a’).click(function() {

    without it all links are overridden and get the selected class applied onClick.

    Many thanks.

  • Pingback: GoTop’s Blog » 解决使用simplexml_load_string()读取RSS时出现warning : xmlParseEntityRef: no name in xxxxx的问题

  • http://bakais.com Alkindy

    Thank you for this useful tips. I understood all of it apart of the javascript.

  • http://www.magentoconnect.us/ Magento Development

    Thank for the such nice information, it is really a useful for the people who wants to display their blog feed on their website.

    Great Work

  • MStalfoort

    Keep in mind though, this doesn’t work if you start harvesting feeds which are served gzip-encoded

    A possible solution is to use a method like this:

    function get_url_contents($url){

    $crl = curl_init();

    $timeout = 5;

    $useragent = “Googlebot/2.1 ( http://www.googlebot.com/bot.html)”;

    curl_setopt ($crl, CURLOPT_USERAGENT, $useragent);

    curl_setopt ($crl, CURLOPT_ENCODING, “gzip,deflate”);

    //curl_setopt ($crl, CURLOPT_ENCODING, “compress;q=0, gzip;q=0″);

    curl_setopt ($crl, CURLOPT_URL, $url);

    curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);

    $ret = curl_exec($crl);

    curl_close($crl);

    return $ret;

    }

  • anurag bhatia

    not a good explanation………

  • clement

    how to open feed in a new tab

  • http://www.brianbatesd.com Brian

    Awesome tutorial. Needed a lightweight solution that wasn’t SimplePie for a mobile site and this worked perfect on my first try. Thank you!

  • Sam Riche

    Great tutorial! It was very helpful! But I do have a question:

    I am attempting to use it to also display the CONTENT of a page. But because the tag for the content includes a colon (content:encoded), I can’t seem to just drop it into the code. It’s clearly getting hung up on that part.

    For simple testing purposes, I am just using the same code you presented. (Actual style stuff can come later).

    foreach($x-&gtchannel-&gtitem as $entry) {
    echo “&ltli&gt&lta href=’$entry-&gtlink’ content:encoded=’$entry-&gttitle’&gt” . $entry-&gtcontent:encoded . “&lt/a&gt&lt/li&gt”;
    }

    • Sam Riche

      The code section came out all wonky, so here’s the line of code I’m using:

      echo “$entry->content:encoded”;

      All it does is display “:encoded” to the screen. I assume there’s some way to keep it from breaking the line at the colon, but I’m still too green to know what it is. I’ve dug around, but can’t figure it out. Any help would be appreciated. Thanks!

  • http://devlup.com jeyaganesh
  • http://stackoverflow.com/questions/8078864/read-array-data-from-rss om nath

    please tell me how can i read this data

  • om nath
  • http://www.kkg04.co.cc/ wawan

    thanks for your sharing…

  • Alex

    How Can I set a limit of feed? For example: max 5 link

    Thank you very much

    • Mike Smith

      I was also looking for the same as Alex.

      How to limit the number of feeds being displayed? Because some feeds has more than 10 feeds in it. So I want to limit to 5 for example.

      Please give me some idea on how to achieve that.

      Thanks.

      • shikhar

        do this to limit the number of feeds and also show the content below the the title

        <?php
        $i=0;
        echo "”;

        foreach($x->channel->item as $entry) {
        echo “link’ title=’$entry->title’>” . $entry->title . ““;
        echo “$entry->description”;
        $i++;

        if($i==3)
        {break;
        }

        }
        echo “”;

        //to set $i in the if condition to the number of posts you want to display.

        hope this helps…

        ?>

  • http://www.weblogtoday.com Johan Balk

    Does this tutorial still works with the latest php build 5.x, because it seems that this is an old tutorial written in 2008?

  • aneeq

    There are several ways to read RSS feed in PHP, but this one is surely one of the easiest.

    channel->item as $entry) {
    echo “link’ title=’$entry->title’>” . $entry->title . “”;
    }

    ?>

    Source:
    http://phphelp.co/2012/04/23/how-to-read-rss-feed-in-php/
    OR
    http://addr.pk/a0401

  • http://www.jsifalda.name/ JSifalda

    What is the better and faster way?

    $content = file_get_contents($url);
    $xml = new SimpleXmlElement($content);

    or

    $xml=simplexml_load_file($url);

  • Shoaib

    Great tutorial….:)))

  • nghiep

    my problem is
    Warning: SimpleXMLElement::__construct() [simplexmlelement.--construct]: Entity: line 1: parser error : Start tag expected, ‘<' not found in \workingWithRSSFeeds\includes\functions.php on line 7

    where is fail in error at website provide rss or my code?

  • Davinder Singh

    how to get data of a particular item….

  • http://www.facebook.com/uditnarayansharma Udit Sharma

    nice tutorial

  • Siva

    Hi ,

    Great Tutorial

    I have one Question ??

    How to display the particular news to other page(not news – source page )

  • rheda zhu

    I want to keep the rss title, url, content, key, and the date it was made rss automatically saved into the database, and display on the index page title, url, content, key, and the date is taken from the database rss

  • Elijah

    This is exactly what I’ve been looking for in order to add a simple, very scalable, RSS feed reader. So easy to style too, great job!