Personally I’m not a huge fan of Twitter, but it is all the rage at the moment and even a cynic like me can see that it’s a valuable tool for connecting with your clients. In fact, there was so much buzz about the launch of Everything You Know About CSS Is Wrong! that we’ve added a simple “Twitter Buzz” widget to it’s sales page.

While building my little widget I couldn’t find anything quite like what I was after, so I threw something together with PHP and jQuery, and now I’d like share it with you.

The Server-Side Twitter Proxy

This one’s dead simple. Check it out:

<?php
header("Content-Type: text/xml");
// replace Foobar with your URL-encoded search term
echo(file_get_contents(
    "http://search.twitter.com/search.atom?q=Foobar"));
?>

Here we simply grab the search results from http://search.twitter.com/search.atom?q=Foobar, and return it straight to the client. We also set the content type of the response to text/xml; without this, jQuery doesn’t know to handle the response as an XML DOM Document.

Client-Side Twitter Buzz Widget

With our server-side proxy and jQuery in place, we can start injecting the response into our document. Place a hidden div with the id twitter-buzz somewhere in your document, then include the following JavaScript:

$(function() {
    $.get("twitter-proxy.php", function(data, status) {
      // check for success
      if(status == "success") {
        // check for entries
        if($("entry", data).size() > 0) {   
          // create the list               
          var list = $("<ul>").get(0);
          // iterate through entries
          $("entry", data).each(function(index, entry) {
            // parse out the details of the tweet
            var authorElement = $("author", entry).get(0);
            var authorName = $("name", authorElement).text();
            var authorUri = $("uri", authorElement).text();
            var authorImage = $("link[rel='image']", entry).attr("href");
            var text = $("title", entry).text();
            // add the tweet to our list
            $(list).append("<li><a href="" + authorUri + "">" +
                "<img src="" + authorImage + "" alt="" + authorName + "" />" +
                "</a><span>" + text + "</span>");
          });
          // add the list to the document
          $("#twitter-buzz").append(list);
          // reveal the area
          $("#twitter-buzz").show("slow");
        }
      }
    });
});

This simply grabs the Atom response from the Twitter proxy we created earlier, creates an unordered list of tweets, then adds them to the document. Even if something goes wrong, or the search returns zero tweets, the page won’t be corrupted at all; all we’ll have is a hidden, empty div in the page.

There are certainly improvements that could be made to this widget, such as adding automatically refreshing itself on a timer and automagically adding links for @replies, but I’ll leave adding these features up to you.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.


  • Raena Jackson-Armitage

    If you’re hosted in a place where fopen and the like aren’t allowed, you can also do the proxy with curl. It’s not as stupendously simple, but it does get around that restriction.

    
    <?php
    
        header("Content-Type: text/xml"); 
    
        $twitter = "http://search.twitter.com/search.atom?q=Foobar"; 
        echo get_some_contents($twitter);
    
    function get_some_contents($site_uri) {
        $curly = curl_init();
        // adjust this timeout to taste 
        $timeout = 5;
        curl_setopt ($curly, CURLOPT_URL, $site_uri);
        curl_setopt ($curly, CURLOPT_CONNECTTIMEOUT, $timeout);
        // time for output
        ob_start();
              curl_exec($curly);
              curl_close($curly);
              $got_contents = ob_get_contents();
        ob_end_clean();
    
        return $got_contents;
    }
    
    ?>
    

    Apologies for any weird smart quotes that snuck in there.

  • http://www.para-diddledesign.com somecallmejosh

    I’m with you on the Twitter thing. It feels very contrived.

  • http://kennygrant.ca funky house

    to Raena Jackson-Armitage:

    so glad i finally got curl installed and working properly.. do not want to touch or recompile apache again.

    thanks for the tip!

Learn JavaScript for free!
Free course: Introduction to JavaScript

Yours when you take up a free 14-day SitePoint Premium trial.