Get Your Most Recent Twitter Status Using PHP
Written by Cory S.N. LaViska on June 22nd, 2008
A PHP function that will return someone’s current Twitter status.
I wanted a very simple PHP function to return my current Twitter status so I could put it on my website. Alas, every solution I found online required an XML parser. Of course, they all returned a lot more than the most recent status, but I didn’t want any of that.
Since my updates are not protected (i.e. they appear in the public timeline), I knew I could use Twitter’s API to obtain my status without authenticating. The URL to access this information is http://twitter.com/statuses/user_timeline/id.format, where id is your numerical Twitter ID and format is one of xml, rss, json, or any other format supported by the API.
To find your numerical Twitter ID, login to Twitter and click on your RSS feed (bottom of the page). The URL will look something like http://twitter.com/statuses/friends_timeline/12345678.rss. Your ID will be the 12345678.
The following PHP function accesses the specified timeline and returns only the most recent (current) update.
function twitter_status($twitter_id, $hyperlinks = true) {
$c = curl_init();
curl_setopt($c, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/$twitter_id.xml");
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$src = curl_exec($c);
curl_close($c);
preg_match('/<text>(.*)<\/text>/', $src, $m);
$status = htmlentities($m[1]);
if( $hyperlinks ) $status = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"\\0\">\\0</a>", $status);
return($status);
}
?>
Note the $hyperlinks parameter, which will enable/disable anchor tags from appearing in your statuses when they contain a URL.
Also note that this function requires the PHP cURL library, which is enabled by default on most shared web hosts.
Sometimes Twitter can be a little slow, and using this function on your webpage when Twitter is lagging will cause your page to lag. I found it best to call this function via AJAX after your page loads to prevent such lag times.


Comments
#1 Harsh on Jul 29th, 2008