Get your last tweet in PHP
I did have a script which pulled my last tweet, and added it to a speech bubble coming from a picture of me. I took it off since it took too long on a slow connection to get the image. However, this little nugget of code will pull the last tweet for you (or whoever you want) for your evil deeds:
$twitee = 'ajdixon'; // The person you want to grab the status of
$ch = curl_init();
$url='http://twitter.com/statuses/user_timeline/';
$url.=$twitee.'.json?count=1';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$tweet = json_decode($data);
$date = strtotime($tweet['created_at']);
$text = $tweet['text'];
This will give you the text in the $text variable, and a unix timestamp of when the message was posted. You can do a print_r($tweet); to see what other nuggets of wonder you can get about a tweet.
I had a problem where I did not have a json_encode function, so below is a substitute:
function json_decode($json)
{
$comment = false;
$out = '$x=';
for ($i=0; $i<strlen($json); $i++)
{
if (!$comment)
{
if ($json[$i] == '{') $out .= ' array(';
else if ($json[$i] == '}') $out .= ')';
else if ($json[$i] == ':') $out .= '=>';
else $out .= $json[$i];
}
else $out .= $json[$i];
if ($json[$i] == '"') $comment = !$comment;
}
eval(str_replace('[','',str_replace(']','',$out)) . ';');
return $x;
}
and this function gives you something along the lines of ‘30 minutes ago’:
function relativeTime($timestamp){
$difference = time() - $timestamp;
$periods = array("sec", "min", "hour", "day", "week", "month", "years", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
if ($difference > 0) { // this was in the past
$ending = "ago";
} else { // this was in the future
$difference = -$difference;
$ending = "to go";
}
for($j = 0; $difference >= $lengths[$j]; $j++) $difference /= $lengths[$j];
$difference = round($difference);
if($difference != 1) $periods[$j].= "s";
$text = "$difference $periods[$j] $ending";
return $text;
}
So, a small bit of code such as:
echo $text.' ('.relativeTime($date).')';
Will show something like this:
This is the last tweet by @ajdixon! (32 minutes ago)
Oh the fun you can have with twitter is endless….