On Aug 31st 2010 Twitter changed its way that applications could authenticate with it – it now uses OAuth http://blog.twitter.com/2010/08/twitter-applications-and-oauth.html
In a previous post, Display your last tweet using PHP & Twitter API
I had suggested use the cURL command in php to send the Twitter username & password to authenticate with the Twitter API to retrieve the xml of the status updates.
However this no longer works with the coming of OAuth – a problem that some of my clients noticed over the past couple of days.
So how to fix this? Well I looked into the scant (and baffling) documentation on OAuth, and downloaded a library or too for php implementation of the Twitter OAuth, but I had this nagging feeling I was using a hammer to crack a nut. Surely anyone can see what my last Twitter update is just by going on Twitter – they don’t need to be logged in?
Then it hit me – that the xml that was being returned could be read using a feed reader like good old SimplePie!
I know it works on the 1&1 hosting that myself and my clients use. I know that you can read Twitter statuses in a feed reader (like Google Reader) so it must be possible.
So thanks to this hugely helpful post here:
http://www.sitepoint.com/blogs/2009/09/29/build-a-lifestream-with-simplepie/
I’ve written the following function that allows you to get the last Tweet of a particular Tweeter:
<?php
require_once('includes/modules/simplepie.inc');
$cache = "/cache";
$duration = 1800;
// snipe's twitterify function turns links into clickable goodness
// http://www.snipe.net/2009/09/php-twitter-clickable-links/
function twitterify($ret) {
$ret = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1<a
href=\"\\2\">\\2</a>", $ret);
$ret = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1<a
href=\"http://\\2\">\\2</a>", $ret);
$ret = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1
\">@\\1</a>", $ret);
$ret = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?
q=\\1\">#\\1</a>", $ret);
return $ret;
}
function getLastTweet($username){
$twitter = new SimplePie("http://twitter.com/statuses/user_timeline/$username.rss", $cache, $duration);
foreach ($twitter->get_items(0,1) as $item) :
echo twitterify(str_replace("$username: ", "", $item->get_title
()));
endforeach;
}
?>
<?php getLastTweet("GriffithsHire");?>