How To: Build a Simple RSS Reader with JQuery


This one’s from my Mashups class. The first project, was to build an RSS Reader. I’ve already posted a quick tutorial on how to build an RSS reader with Adobe Flex. Here’s a simple one that uses JQuery to get the feeds and then loop through them to output them to the browser window. Piece of cake for many of you, yes, but if you have never used anything but the DOM and plain ol’ JavaScript, you may be scared by the whole AJAX fad on teh intarwebs these days. JQuery makes it super easy to look like a Javascript rockstar. I teach a lot of students that haven’t ever touched a library of code like JQuery before, so tutorials like this are pretty valuable to some readers..

First, create an XHTML file.

<!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" xml:lang="en" lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Untitled</title>
</head>
<body>
</body>
</html>

Then, download my favorite JavaScript API, JQuery.

Link the JS file in by adding this tag in the head:

<script type="text/javascript" src="jquery-1.2.6.min.js" charset="utf-8"></script>

Once we have JQuery linked in, it’s time to write some HTML… I created a couple <div> elements to act as wrappers/containers for the page’s content. I used an <img> to put a nice graphic header in the page, then added some semantic XHTML elements, an <h1> for the text header, a <form> tag to hold a <select> menu populated with a few of my favorite Flash blogs as the <option> elements setting their URLs as the value attributes for those, and of course a <label> to let everyone know they should “Select a Feed” via that menu. After the tags are closed, I put one more div after the form to contain the feed results after they are retrieved. I add id attributes liberally throughout the tags, as I may need to style them or use them in my JQuery reader soon, *hint* *hint*.

If you’re following along, your code probably looks something like this:

<!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" xml:lang="en" lang="en">
<head>
	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<title>RSS Reader</title>
	<script type="text/javascript" src="jquery-1.2.6.min.js" charset="utf-8"></script>
</head>
<body>
<div id="container">
<a href="visualrinse.com"><img src="http://visualrinse.com/wp-content/themes/smooth-dirt-10/header_08v2.jpg" alt="Visualrinse" title="Visualrinse.com" /></a>
<div id="ui">
<h1>Flash Feed Reader</h1>
<form id="selectParser" action="">
<label>Select a feed:</label>
<select id="diffFeeds">
	<option value="">Select</option>
	<option value="http://feeds.feedburner.com/aralbalkan">Aral Balkan</option>
	<option value="http://www.bit-101.com/blog/?feed=rss2">Bit-101</option>
	<option value="http://feeds.feedburner.com/peterelst/">Peter Elst</option>
	<option value="http://www.gskinner.com/blog/index.xml">Grant Skinner</option>
	<option value="http://blog.andre-michelle.com/feed/">Andre Michelle</option>
	<option value="http://feeds.feedburner.com/flashmagazine/rss2">Flash Magazine</option>
	<option value="http://casario.blogs.com/mmworld/rss.xml">Marco Casario</option>
	<option value="http://www.sephiroth.it/weblog/index.xml">Sephiroth</option>
	<option value="http://www.quasimondo.com/index.xml">Quasimondo</option>
	<option value="http://feeds.feedburner.com/sebleedelisle">Seb Lee-Delisle</option>
	<option value="http://osflash.org/feed.php">OS Flash</option>
</select>
</form>
</div>
<div id="feedContent">
	&nbsp;
</div>
</div>
</body>
</html>

Cool… So, time to add the interactivity. We’re going to add a script tag to the head area and begin writing a Javascript function. I called mine “get_rss_feeds()”. The basic idea behind the function is to use the JQuery api’s “get()” function to grab the URL of the selected item from feedList (the name of our select menu, remember?), then run through each item in the RSS feed, putting those tasty XML elements from the feed like title, pubdate and description into HTML and popping them on the page. Between runs, we’ll need a way to clear out the div containing the content, so each time a new feed loads, the old content is removed.

So to do this, let’s put the following code in the Javascript block:

function get_rss_feed() {
	//clear the content in the div for the next feed.
	$("#feedContent").empty();
 
	//use the JQuery get to grab the URL from the selected item, put the results in to an argument for parsing in the inline function called when the feed retrieval is complete
	$.get($('#diffFeeds').val(), function(d) {
 
		//find each 'item' in the file and parse it
		$(d).find('item').each(function() {
 
			//name the current found item this for this particular loop run
			var $item = $(this);
			// grab the post title
			var title = $item.find('title').text();
			// grab the post's URL
			var link = $item.find('link').text();
			// next, the description
			var description = $item.find('description').text();
			//don't forget the pubdate
			var pubDate = $item.find('pubDate').text();
 
			// now create a var 'html' to store the markup we're using to output the feed to the browser window
			var html = "<div class=\"entry\"><h2 class=\"postTitle\">" + title + "<\/h2>";
			html += "<em class=\"date\">" + pubDate + "</em>";
			html += "<p class=\"description\">" + description + "</p>";
			html += "<a href=\"" + link + "\" target=\"_blank\">Read More >><\/a><\/div>";
 
			//put that feed content on the screen!
			$('#feedContent').append($(html));  
		});
	});
 
};

Now, besure to add the get_rss_feed function call to the feedList’s onchange event and you are good to go. With a catch, of course. This will only work when accessed locally via the “file://” protocol. IN order to use this online, you’ll need to circumvent the browser security sandbox and use a middleware proxy to grab the XML and make it local. Here’s the PHP:

<?php
	// PHP Proxy
	// Loads a XML from any location. Used with Flash/Flex apps to bypass security restrictions
	// Author: Paulo Fierro
	// January 29, 2006
	// usage: proxy.php?url=http://mysite.com/myxml.xml
 
	$session = curl_init($_GET['url']); 	               // Open the Curl session
	curl_setopt($session, CURLOPT_HEADER, false); 	       // Don't return HTTP headers
	curl_setopt($session, CURLOPT_RETURNTRANSFER, true);   // Do return the contents of the call
	$xml = curl_exec($session); 	                       // Make the call
	header("Content-Type: text/xml"); 	               // Set the content type appropriately
	echo $xml; 	      // Spit out the xml
	curl_close($session); // And close the session
?>

Slick, eh? To use it, simply prepend the proxy’s URL used in the $.get call, like this:

$.get('proxy.php?url='+$('#diffFeeds').val(), function(d) {

So, there you go. Add some CSS in there and it’s all stylish. You can the feed reader in effect here.

Hope you enjoyed this.

[del.icio.us] [Digg] [dzone] [Facebook] [Google] [Newsvine] [Reddit] [StumbleUpon] [Technorati] [Twitter] [Yahoo!]

Posted on


28 comments

  1. Gary F Sep 25

    It’s a pity a server-side proxy is needed to get around x-domain scripts that grab an XML file. I’ve been searching for a jquery based RSS reader so thanks for that.

  2. Mircea Oct 8

    Can this reader be used with Prototype instead jQuery?

  3. cherryaa Nov 25

    I’ve been struggling with ajax for the longest time … I knew it must be all common sense really, but couldn’t find my way through the mystique!

    You’ve clarified EVERYTHING for me!

    Just ….. thank you :) )

  4. Stevie Benge Dec 10

    Hey. Thanks for this. It works well. However I have noticed that the script doesn’t seem to like feeds from Feedburner… It won’t display anything for a feed coming from Feedburner. I checked your demo page and it’s also not displaying any Feedburner feeds. I know some Google properties have been kind of flaky this week but do you have any idea what might be happening?

  5. Chad Dec 10

    Stevie,
    Thanks for the visit.

    I believe the feedburner issues has to do something with the feeds possibly including images/rich media (full HTML markup, etc). When the feeds are truly valid RSS with no embedding HTML markup they seems to parse fine, however, put some extras in there like IMG tags, etc and things fail. I don’t have a simple quick answer for you but you might want to look into cleaning up the input/scrubbing the markup that JQuery grabs.

    Hope this helps!

  6. Stevie Benge Dec 10

    Chad:

    Thanks for the tip, I appreciate the response. I will give your suggestion a try…

  7. flep Apr 2

    Hi!
    How do I limit the numbers of items that i want to show? For example, my feed return 10 items, but i want to show just 5.

    Thanks!

  8. Pedro Apr 14

    I copied the tutorial to a “t” and Im not getting the feed contents.Any idea?

  9. Ray Aug 27

    I am having the same issue as Pedro.

    Some details:

    I think my issue is the PHP script. When I debug the page, I see that it throws a warning that Resource interpreted as other but transferred with MIME type text/html. Not sure what to do about that as the page is set up as it should be. Is this something that needs to be addressed on the server?

  10. Chad Aug 27

    Ray, do you have a URL I could check this out at?

  11. Ray Aug 27

    Hi Chad.. I sure do..

    I must admit that I kinda am using the css from this page as I copied everything except the jquery location… please forgive :-)

    http://www.buzzworthytravel.com/portals/11/honeymoonregistry/js/testit.htm

  12. Gasim Oct 12

    didn’t work , can any one upload the code or email it to me silu44@gmail.com

  13. Gasim Oct 15

    i did like you creating html and link css and jquery-1.2.6.min.js also add script tag and write the code

    then nothing work where to put the php for proxy and how to call it

  14. Peter Ellis Oct 15

    For anyone reading this you might alos want to check out the following link:

    http://jquery-howto.blogspot.com/2009/04/cross-domain-ajax-querying-with-jquery.html

    If you are having trouble retrieving a feed from an external site/link e.g. a bbc news feed!

  15. Truong Quang My Oct 18

    Thank you very much!
    You is very good. You should write same document. You’s more than yahoo developmen. It’s hide almost skill.
    I speak English very bad.

  16. anirudha Nov 5

    I like it but i can’t do it are you write this post for html with jquery thanks for post

  17. Jeremy Feb 3

    Thanks! This is a great solution.

    I’m having issue trying to read content:encoded. It is fine with the description, but I want to display the full content. Any ideas?

  18. Adam Feb 21

    Thanks for all the info! Great solution.

    I’ve been trying to get it to only display the top 3 (newest) posts from a feed. Any Suggestions?

  19. Chad Feb 21

    Jeremy, not sure exactly, but it looks like a lot of people seem to be having those same issues.
    http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=jquery+content:encoded

    Adam, take a look at the “$(d).find(‘item’).each(function() {” line. That line tell JQuery to loop over the whole array. You can add a conditional in the loop to “return” you out after it loops 3 times, etc.

  20. Pacquiaio vs Clottey Feb 26

    Two thumbs up! Very wonderfull tool.

  21. Mike Danna Mar 5

    Very nice, this solution worked perfectly. Definitely a keeper.

    Thanks for sharing!

  22. christolo Mar 11

    Really nice work.

  23. John Mar 12

    Quite frustrating. Can’t get it to work. And when I look at your source code for your code for the working example link about, it differs from that posted for this tutorial. Obviously the problem is I don’t know enough about jQuery/php, but you do a great job, taking it step by step, and then, for no obvious reason, miss out a few steps.
    Thanks anyway, I’m aware it’s my shortcomings!

  1. 50+ jQuery Tutorials und mehr f?ēr Einsteiger und Fortgeschrittene
  2. Creating a jQuery RSS Aggregator (reader) | Benzing Technologies | Creative Web Design, Affordable Web Hosting, SEO, Social Media Marketing
  3. javascript effects | WebDesignExpert.Me
  4. Creating a jQuery RSS Aggregator (reader) « Benzing Technologies
  5. Top 14 jQuery Photo Slideshow / Gallery Plugins | Theme Center

Leave a reply

Related Posts:

  • links for 2009-04-04
  • Been Crazy Busy… A Few Updates
  • links for 2009-02-24