Monday, 5 October 2009

Display your last tweet using PHP & Twitter API

Well I figured it would be easy to do - so why has it taken me most of the afternoon to figure it out?!

I was looking for a way to simply get the text of my last Twitter "tweet" and then use the text within my site somewhere.

Ok I shall fess up - the reason I really wanted to know how to do this was for a client who needed to be able to update one line of text on his website, so he can have a lovely ticker tape banner across his site (I kid you not!) - but he didn't have the budget (or technical know how) to have & use a CMS for his web site - anyway it would be like using a hammer to crack a nut, right?

So I though maybe if I could use the last Tweet he posted in his Twitter account it might be a nice way of getting him to write more on Twitter (great marketing potential yadda yadda...) and a natty way of giving him a mini CMS!

So after a lot of searching - and finding some very complicated solutions doing all manners of things with the Twitter API (which is very mysteriously documented if you ask me) I came up with the following solution - a PHP function that returns the last tweet.

(Note the XML parser I use is only available in PHP5)




function twitterCapture() {

// Set your username and password here
$user = 'YOURUSERNAME';
$password = 'YOURPASSWORD';

$ch = curl_init("http://twitter.com/statuses/user_timeline/USERNAMETOFOLLOW.xml");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch,CURLOPT_TIMEOUT, 30);
curl_setopt($ch,CURLOPT_USERPWD,$user . ":" . $password);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
$result=curl_exec ($ch);
$data = strstr($result, ' $xml = new SimpleXMLElement($data);
return $xml->status[0]->text;

}

echo twitterCapture();


?>




Kudos goes to this post for starting me off:
http://blarnee.blogspot.com/2009/09/this-is-test.html

There's probably an easier way of doing this - so I'm interested in any feedback

Here it is in action:
http://www.kineticpulse.co.uk/twitter5.php5