Advertisement
  1. Web Design
  2. HTML/CSS

How to Read an RSS Feed With PHP - screencast

Scroll to top
Read Time: 8 min

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.

CollisCollisCollis

Our naked skin

Tab FinalTab FinalTab 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 StructureFile StructureFile 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.

1
2
<?php
3
4
function getFeed($feed_url) {
5
	
6
	$content = file_get_contents($feed_url);
7
	$x = new SimpleXmlElement($content);
8
	
9
	echo "<ul>";
10
	
11
	foreach($x->channel->item as $entry) {
12
		echo "<li><a href='$entry->link' title='$entry->title'>" . $entry->title . "</a></li>";
13
	}
14
	echo "</ul>";
15
}
16
?>

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

1
2
function someName($parameters) {
3
...some method
4
}

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:

1
2
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".

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

1
2
function getFeed($feed_url){
3
4
}

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

1
2
<?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.

1
2
$x = new SimpleXmlElement($content);

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

1
2
	echo "<ul>";
3
	
4
	foreach($x->channel->item as $entry) {
5
		echo "<li><a href='$entry->link' title='$entry->title'>" . $entry->title . "</a></li>";
6
	}
7
	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 InfoRSS InfoRSS 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.

1
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
4
<html xmlns="http://www.w3.org/1999/xhtml">
5
<head>
6
    <title></title>
7
	<link rel="stylesheet" href="css/default.css" />
8
	<script src="js/jquery-1.2.6.pack.js" type="text/javascript"></script>
9
	<script src="js/myScript.js" type="text/javascript"></script>
10
</head>
11
<body>
12
<?php require_once "includes/functions.php"; ?>
13
<div id="wrap">
14
15
<ul id="nav">
16
<li><a href="#content_1" class="selected">NETTUTS</a></li>
17
18
<li><a href="#content_2">ThemeForest</a></li>
19
<li><a href="#content_3">Screencasts</a></li>
20
</ul>
21
22
	<div id="mainContent">
23
24
		<div id="content_1">
25
			<?php getFeed("http://feedproxy.google.com/nettuts"); ?>
26
		</div><!--end content 1-->
27
28
		<div id="content_2">
29
			<?php getFeed("http://feedproxy.google.com/themeforest"); ?>
30
		</div><!--end content 2-->
31
32
		<div id="content_3">
33
			<?php getFeed("http://feeds.feedburner.com/NETTUTSVideos"); ?>
34
		</div><!--end content 3-->
35
36
	</div><!--end main content -->
37
38
</div><!--end wrap-->
39
</body>
40
</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 nowwhat we have nowwhat we have now

Implementing the Tabs With jQuery

jQuery WebsitejQuery WebsitejQuery Website

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

1
2
$(function() {
3
    $('#mainContent div:not(:first)').hide();
4
5
    $('ul li a').click(function() {
6
        $('ul#nav li a').removeClass('selected');
7
        $(this).addClass('selected');
8
9
        var href = $(this).attr('href');
10
        var split = href.split('#');
11
12
        $('#mainContent div').hide();
13
        $('#mainContent div#' + split[1]).fadeIn();
14
15
        return false;
16
    });
17
});

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.

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

1
2
$('#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
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Web Design tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.