Advertisement

How to Read an RSS Feed With PHP - screencast

by

This Cyber Monday Tuts+ courses will be reduced to just $3 (usually $15). Don't miss out.

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


Advertisement