Twitter widget to show your latest tweets in carousel slider

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

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
   $query = "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($query);
   $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:


You might also like:



Enjoyed this article?

Share on Google+

This entry was posted in Jquery, PHP. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.
  • http://www.register-domainname.in/ Buy Domain Names

    Good idea..So that we can keep track of the recent tweets we made..

  • Anonymous

    Bob your  carousel slider on the homepage doesnt seem to work ??

    • http://bobbelderbos.com/ Bob Belderbos

      yes, I noted, kind of weird, need to look into it. anyone that used the code has the same issue?

      • Anonymous

         Is it some kinda issue with the YQL ??

        • http://bobbelderbos.com/ Bob Belderbos

          not sure, some weeks ago the query would always return the results in the console, but in the widget is another story. not a priority now for me, the homepage does not suffer under this, let me know if you find something more … thanks

          • VirendraRajput

            I was thinking to use YQL for an app but since I m having so much of issues with it ! I m thinking to an alternative for it.

          • http://bobbelderbos.com/ Bob Belderbos

            YQL didn’t misbehave except this one. It is still a powerful tool, I still like it

          • VirendraRajput

             I dont know why but it sometimes stops responding to the queries. I tested it both on the local server as well as my web server.
            I even tried to ask on the YQL forums but didn’t get any response there !!!

          • http://bobbelderbos.com/ Bob Belderbos

            thanks for your investigations. I will try it at some other time. what alternatives do we have? honestly working with individual APIs is not that painful for me …

          • VirendraRajput

             YQL is really great !! But isint dependable !!

          • http://bobbelderbos.com/ Bob Belderbos

            You are right :)

  • Links

  • Post categories

  • Bob’s Reading List

  • My Facebook Apps

    hi folks, what are you reading?

    sharemovi.es: tell your friends about your favorite movies

    Friends Jukebox | Create a Jukebox based on the Music your Friends like!