Today I show you a script to display the latest tweets on your website or blog. You can use two ways: make a call to Twitter's user_timeline or use YQL/ search.twitter. I will wrap the results in the Tiny Carousel jQuery plugin. Read on ...

Start & issues

New here? You might want to subscribe to my blog by email or RSS.

I started simple with a an import of Twitter user_timeline with file_get_contents (from URL: http://twitter.com/statuses/user_timeline/bbelderbos.json?count=5), based on this post. However, although this worked perfectly on localhost, on my remote server it did not. Besides, I soon got a Rate limit exceeded response from Twitter (which does not make sense because at least I should have 150 requests per hour) You can get the code here.

Alternative solution: YQL

featured image

Recently I blogged about YQL, a powerful way to crawl the internet. Twitter is well represented among its tables. So I applied what I learned to get my tweets via the search.twitter table in YQL. See the code below: yql.php does the heavy lifting. Instead of file_get_contents (which I would use normally), I use curl to get the URL content. That seemed to work better with my remote server. It returns JSON (you can also choose XML or RSS, but JSON is said to be fastest). Use json_decode to parse JSON into an array. You see some commented lines you can uncomment to print debug info in case you have any issue. I use the Tiny Carousel jQuery plugin to show the results in a nice slider.

Full code display

== yql.php ==

   <?php
   $q = "select text,profile_image_url from twitter.search where q='from:@bbelderbos' limit 10";
   $url = "http://query.yahooapis.com/v1/public/yql?q=";
   $url .= rawurlencode($q);
   $url .= "&format=json&env=store://datatables.org/alltableswithkeys";
   
   // using curl, as file_get_contents sometimes fails on remote server
   // $json = file_get_contents($url, true);
   $json = get_data($url);
   
   $info = json_decode($json, true) ;
   // debug, if json_decode fails
   // $error = json_last_error(); echo $error; exit;  
   // debug, check structure result
   // echo "<pre>"; print_r($info ); echo "</pre>"; exit; 
   
   // function to get URL via cURL
   // from: http://davidwalsh.name/download-urls-content-php-curl
   function get_data($url) { 
     $ch = curl_init();
     $timeout = 5;
     curl_setopt($ch,CURLOPT_URL,$url);
     curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
     curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
     $data = curl_exec($ch);
     curl_close($ch);
     return $data;
   }
   ?>

Roll your own YQL query at the YQL console:

yql query

== index.php ==

  <?php include 'yql.php'; ?>
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
   
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Last Tweets @bbelderbos</title>
    <link rel="stylesheet" href="style.css" type="text/css" media="screen"/>
   	
    <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
    <script type="text/javascript" src="js/jquery.tinycarousel.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function(){
        $('#slider1').tinycarousel({ pager: true, interval: true, intervaltime: 5000  });	
      });
    </script>	
   		
    </head>
    <body>
      <div id="slider1">
   	<div class="viewport">
   	  <ul class="overview">
   	    <?php 
   	    foreach($info['query']['results']['results'] as $tweet) {
   	      $tweetText = $tweet['text'];
   	      $avatar = $tweet['profile_image_url'];
   	      
              // URLs (from http://www.phpro.org/examples/URL-to-Link.html)
   	      $tweetText = preg_replace("/([w]+://[w-?&;#~=./@]+[w/])/i","<a target="_blank" href="$1" target="_blank">$1</a>",$tweetText);
   
   	      // twitter handles
   	      $tweetText = preg_replace('/(@S+)/i',"<a target="_blank" href="http://twitter.com/$1" target="_blank">$1</a>",$tweetText);
   
             // hash tags map to search?q=#hash
   	     $tweetText = preg_replace('/(#)(S+)/i',"<a target="_blank" href="http://twitter.com/search?q=%23$2" target="_blank">$1$2</a>",$tweetText);	
   
   	     echo '<li><a href="http://twitter.com/bbelderbos" target="_blank"><img src="'.$avatar.'" alt="bob avatar"></a><p>'.$tweetText . "</p></li>";
   				}
   	   ?>
   	 </ul>
       </div>
     </div>
   </body>
   </html>

The preg_matches are to turn handles (@), hash tags (#) and links into URLs. I am not expanding on the CSS in this post, let me know if you have any questions.

Check it out:


Bob Belderbos

Software Developer, Pythonista, Data Geek, Student of Life. About me