Get $500+ of the best After Effects files, video templates and music for only $20!
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.


Add Comment

Discussion 86 Comments

Comment Page 2 of 2 1 2
  1. indrajit says:

    it helped me to use other tools, flash wizards

  2. NinNin says:

    Work well but not with feedburner url.

  3. Dodant says:

    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?

  4. Dodant says:

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

    So changed the line to:

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

  5. فارکس says:

    thanks , it helped me parsing rss with php

  6. Wim says:

    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!

  7. Bryan says:

    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

  8. Joe says:

    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 says:

      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…

  9. Les says:

    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?! ;)

  10. Lam Nguyen says:

    Thanks, this tuts is great!

  11. Steve says:

    great tut!

  12. art.mania says:

    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? :/

  13. caoson148 says:

    -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…”;
    }
    }
    ?>

  14. Alexis says:

    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.

  15. Alkindy says:

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

  16. 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

  17. MStalfoort says:

    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;

    }

  18. anurag bhatia says:

    not a good explanation………

  19. clement says:

    how to open feed in a new tab

  20. Brian says:

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

  21. Sam Riche says:

    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 says:

      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!

  22. om nath says:

    please tell me how can i read this data

  23. wawan says:

    thanks for your sharing…

  24. Alex says:

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

    Thank you very much

    • Mike Smith says:

      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.

  25. Johan Balk says:

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

  26. aneeq says:

    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

  27. JSifalda says:

    What is the better and faster way?

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

    or

    $xml=simplexml_load_file($url);

  28. Shoaib says:

    Great tutorial….:)))

Comment Page 2 of 2 1 2

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.