Tweetlight: il migliore twitter parser per mostrare i propri tweets
Diciamo la verità: il widget widget di twitter per mostrare, sul proprio sito o blog, i nostri ultimi tweet (ovvero la timeline), è abbastanza brutto.
Non permette la personalizzazione di ogni aspetto, ed è in javascript, cosa che non piace a tutti.
In un pò di tempo libero ho scritto un twitter parser (cioè un codice che mostra gli ultimi tweets di un utente), e l’ho chiamato Tweetlight – A lightweight json twitter parser.
E’scritto in php e sfrutta lo stream contenente gli ultimi tweet in formato json.
Grazie ad una cache, si può impostare il numero di minuti dopo cui bisogna andare a controllare se ci sono nuovi tweets (10 minuti vanno bene).
In questo modo il caricamento è velocissimo, in quanto i tweet vengono letti da un file di cache (tempo di esecuzione dello script: poco meno di 2 millisecondi).
Tweetlight si compone di tre file:
- tweetlight.php: Il codice vero e proprio, in php.
- tweetfunc.inc: Funzioni richieste da tweetlight.php
- output.php: Il file che mostra il risultato finale, l’output, che può essere incollato dove si vuole.
Nel primo file, bisogna inserire il proprio username di twitter nel campo $username, il tempo di durata della cache nel campo $expiretime, ed il numero di tweet da mostrare nel campo $number_tweets.
Vediamo una anteprima di questo file:
<? /* Tweetlight - A lightweight json twitter parser (mean execution ltime less than 2ms, using cache). Set your user name in $username, the number of minutes you want to refresh the cache after in $expiretime (default 10 minutes), and the number of tweets to show in $number_tweets. You can customize the output as you want, this script is meant to be fast, so it doesn't carry any fancy customization. Last rev: 20-apr-11 by flapane.com */ include('tweetfunc.inc'); // functions $username='flapane'; // insert your twitter user name $format='json'; // format $expiretime=10; // cache expire time in minutes $number_tweets=5; // number of tweets to display $cachename="tweetcache_".$username.".json"; //name of the cachefile //create the cachefile if it doesn't exist if (!file_exists($cachename)) { $create = fopen($cachename, 'w'); chmod ("$cachename", 0777); //set chmod 777 fclose($create); } // Is the file older than $expiretime, or the file is new/empty? $FileAge = time() - filectime($cachename); // Calculate file age in seconds if ($FileAge > ($expiretime * 60) || 0 == filesize($cachename)) { // Now refresh the cachefile with newer content (in number equal to $number_tweets) $handle = fopen("http://api.twitter.com/1/statuses/user_timeline/{$username}.{$format}?count=$number_tweets", "r+"); $jsoncontent = stream_get_contents($handle); fclose($handle); $handle = fopen($cachename, 'wb'); fwrite($handle, $jsoncontent); } $tweet=json_decode(file_get_contents($cachename)); // get tweets and decode them into a php array $tweet_avatar = $tweet[0]->user->profile_image_url; //display your twitter avatar echo "<img src='$tweet_avatar' width='30' height='30' alt='twitter avatar' /><b> Last ".$number_tweets." tweets for ".$username."</b><br /><br />"; //output $number_tweets tweets from cache file for ($i=0; $i<=($number_tweets-1);$i++) { $tweet_text = $tweet[$i]->text; //the tweet text $tweet_link = $tweet[$i]->id_str; //twitter status link $posted_at = explode(" ", $tweet[$i]->created_at, 6); //twitter date $some_date = "$posted_at[0] $posted_at[1] $posted_at[2] $posted_at[3] $posted_at[4] $posted_at[5]"; $postedago = adjust_twitter_date($some_date) ."<br />"; //adjust the twitter date output echo "<div id='tweet_text'>".$tweet_text = preg_replace("/(?!(?:[^<]+>|[^>]+<\/a>))\b((http:\/\/)(.*?)\/([\w\.\/\&\=\?\-\,\:\;\#\_\~\%\+]*))\b/is", "<a href=\"\\1\" target=\"\\_blank\">\\1</a>",$tweet_text)."<br /></div>"; //linkify the links in the tweet, and output the tweet echo "<div id='tweet_date'><b><a href='http://twitter.com/$username/statuses/$tweet_link'># posted ".human_time_diff(time(),$postedago) ." ago</a></b></div><br />"; //output the tweet age } ?>
Per chiunque voglia capirne il funzionamento, ci sono i commenti vicino ogni funzione e variabile principale, ed in breve:
- Prende lo stream in formato json
- Controlla se il file di cache è già esistente
- Se il file di cache è recente, usa quello senza aggiornarlo
- Se il file di cache è vecchio, aggiornalo
- Mostra il numero di tweet desiderati
Il file tweetfunc.inc non va toccato, serve per il funzionamento dello script.
La prima volta che si lancia lo script, verrà creato un file di cache del tipo tweetcache_USERNAME.json
Questa è una screenshoot di come apparirà l’output:
Come potete vedere, lo script è “nudo e crudo”, senza customizzazioni via foglio di stile CSS, in modo che sia il più semplice, veloce, e modificabile possibile.
Sta a voi, se volete, modificarne l’aspetto, magari aggiungendo uno sfondo.
Potete scaricare il file zip contenente lo script (E caricarlo sul vostro server ftp) a questo indirizzo: Tweetlight – A lightweight json twitter parser.
Se volete, scrivete un commento con il vostro parere!