A buddy of mine at work today was thinking about the best way to get his latest Twitter update for use on his own site (when he gets round to building it!).
Fortunately, the good folk at Twitter have provided us with XML and JSON streams which can be used to get this pretty easily. I have written a very simple PHP function to get your latest tweet and return it as a string. All you have to provide is your Twitter username. I’m now using this method on my own homepage here on nostin.
The catch is, your web server must be running PHP 5 and have JSON support enabled (JSON is on by default in PHP 5.2 and above) because I’m using the built in json_decode function.
Catch number 2 is that you must also have your tweets unprotected or they won’t show up in the feed without also passing your password with the JSON request. Do remember though that if your tweets are unprotected, anyone can use this method to access your tweets or anyone else who doesn’t protect their tweets too.
The code:
<?php
function get_latest_tweet($username)
{
$path = 'http://twitter.com/statuses/user_timeline/' . $username.'.json?count=1';
$jason = file_get_contents($path);
$arr = json_decode($jason);
$object = get_object_vars($arr[0]);
return $object['text'];
}
?>
I should disclaim that this will only work as long as Twitter continues to provide a JSON feed the way that they currently do. Although there is no reason to think they would change anything, I mean it’s provided for this purpose in the first place but if they alter or desist, this function may discontinue to work.
Comments (5)
+ –