PHP Get your latest Tweet as a string

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)
+ –

This is the cleanest way to do this I've seen. Many thanks.

by Roger from Washington at: 9:32pm 17th Aug 2009

Thank you ...
Really Great Function ...
but how can i get more than 1 tweet ?

by fahad from ksa at: 2:33am 4th Oct 2009

You just change the count at the end of the GET url.

So replace the 1 in $username.'.json?count=1'; to whatever count you want.

by sean from nostin.com at: 10:47am 5th Oct 2009

THANK YOU! I've been looking for this for days and no one has made it simpler than you have. I appreciate your help.

by Steven from SC, USA at: 3:42pm 12th Nov 2009

Even though i'm changing the count to a higher number.. it keeps returning only one tweet. What am i doing wrong?

by W. from NL at: 12:42am 15th Mar 2010