Parsing a Twitter feed with jQuery

Parsing a Twitter feed with jQuery requires two steps:

  1. building a server-side proxy to retrieve the feed
  2. using Ajax to parse the feed.

The proxy's code, written in PHP, is really simple:

tweets.php

<?php
header('Content-Type: text/xml');
$tweets = file_get_contents('http://twitter.com/statuses/user_timeline/120345723.rss');
echo $tweets;
?>

After this, we can use the $.get() method of jQuery to parse this file:

$(document).ready(function() {
 
 
 $.get('tweets.php', function(data) {
 
 
     var $items = $(data).find('item');
     
     $items.each(function() {
     
     
         var $item = $(this);
         var $raw_title = $item.find('title').text();
         var $title = $raw_title.replace('gabromanato:', '').replace(/http:.+/, '');
         var $raw_date = $item.find('pubDate').text();
         var $date = $raw_date.replace('+0000', '');
         var $link = $item.find('link').text();
         
         var html = $('<li></li>').html('<a href="'+$link+'">'+$title+'</a>'+ '<div class="pubdate">'+$date+'</div>');
         
         html.appendTo('#tweets');
     
     
     
     });
 
 
 
 });
 
 
 });

I did this because Ajax cannot fetch a resource located on another domain (this is called same domain policy), so we have to use a Proxy. You can see the final result here.

Leave a Reply

Note: Only a member of this blog may post a comment.