Wednesday, July 29 2009, 17:50
Server-side caching php twitter widget
By fake - Permalink
i was looking for a server-side twitter widget displaying a few tweets for the nachtwerk-online.de page, and i did not find an out-of-the-box solution. the twitter widget on my blog is a javascript client-side thingy. having some php experience i hacked this up (note you need the code below too, for the "niceTimeDiff"-method):
<?php // load the tweets // uses a cache to easen on the twitter server. $twitter_cache_file='/path/to/some/writable/file/twitter_cache.xml'; $mtime= null; if(file_exists($twitter_cache_file)){ $mtime=filemtime($twitter_cache_file); } if($mtime== null ||(time()-$mtime)>(9*60)){// 9 minutes or older? $url=sprintf("http://twitter.com/statuses/user_timeline/%s.xml?count=%d","Nachtwerk_IN",5);// load 5 tweets $content=@file_get_contents($url); if(strlen($content)>0){ $cache_static=fopen($twitter_cache_file,'wb'); fwrite($cache_static,$content); fclose($cache_static); } } $tcontent=@file_get_contents($twitter_cache_file); $all_tweets=array(); if(strlen($tcontent)>0){ $parsed=new SimpleXMLElement($tcontent); foreach($parsedas$status){ $message=preg_replace("/http:\/\/(.*?)\/[^]*/",'\\0',$status->text); $message=ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href=\"\\0\" rel=\"nofollow\">\\0</a>",$message); $tweet=array(); $tweet['timeDiff']= niceTimeDiff($status->created_at); $tweet['message']=$message; $all_tweets[]=$tweet; } } ?>
Of course you will want to replace "Nachtwerk_IN" by your twitter id, and the 5 after it by the nr. of tweets you want to load. The file pointed to by $twitter_cache_file needs to be writable.
urls will be links. the method "niceTimeDiff" is written like this:
<?php function niceTimeDiff($ref_date){ $now=mktime(); $other=strtotime($ref_date); $diffmsecs=$now-$other; $days=$diffmsecs/(60*60*24); $hours=$diffmsecs/(60*60); $minutes=$diffmsecs/(60); $secs=$diffmsecs/1; $ret=""; if($days>1)$ret.=round($days)." days"; elseif($hours>1)$ret.=round($hours)." hours"; elseif($minutes>1)$ret.=round($minutes)." minutes"; elseif($secs>1)$ret.=round($secs)." seconds"; return$ret." ago"; } ?>
Using this code, you will end up with an array called $all_tweets, containing assoziative arrays with 'message' and 'timeDiff' keys. Twitter will be checked every 9 minutes tops.
no comment