Tuesday, September 13, 2011

Process RSS/ATOM Feed on client side through JavaScript

There are few opensource javascript library API available to parse feed data and it gives you result in dom xml or either in JSON format. Once you get the result iterate through feed items and generate you own html markup
1)  Google feed api (http://code.google.com/apis/feed/)- With the Feed API, you can download any public Atom, RSS, or Media RSS feed using only JavaScript, so you can easily mash up feeds with your content. This work for cross domain website.
There is cloud service hosted by google to test this api. http://code.google.com/apis/ajax/playground/#load_feed
Only limitation of google hosted api are you need to generate api key for you server hostname.

2) JQuery JFeed plugins (http://plugins.jquery.com/project/jFeed): 
jFeed is a generic RSS/ATOM feed parser.
jFeed currently parses RSS 0.91, 0.92, 1.0, 2.0 and Atom 1.0 feeds.
Download sample code from here - https://github.com/jfhovinne/jFeed

Other way of displaying feed data is, send ajax request to feed_url use Ajax proxy(http://absolutebrain.blogspot.com/2011/09/ajax-proxy.html) in case of feed_url is pointing to different server and iterate through xml dom elements to get desired element values.
Starting with 1.5 jQuery has built-in xml parsing capabilities, which makes it pretty easy to do this without plugins or 3rd party services.
Sample Code :
<script src="http://code.jquery.com/jquery-latest.js"></script>
<div id="results"></div>
<script language="JavaScript">
    $.ajax({
         type: "GET",
         cache: false,
         dataType: "xml",
         url: "http://localhost:10039/.YouTubeChannel/proxy/http/toi.timesofindia.indiatimes.com/rssfeedstopstories.cms", //Requesting to proxy to get response from timeofindia
         success: function(data) {
             var $xml = $(data);
            $xml.find("item").each(function() {
                $("#results").append($(this).find("title").text()+":"+$(this).find("pubDate").text()+"<br>");
            });
        },
        error : function(jqXHR, textStatus, errorThrown) {
            alert("error: "+textStatus);
        }
   });
</script>

No comments:

Post a Comment