On my homepage, you may notice that I have a bit of code to get my latest tweet for this website’s twitter account. Usually this is blog updates, but it may show other things.

I originally found this code on http://www.phoenixheart.net/2009/05/code-snippet-1-get-latest-tweet/. Since twitter has been having issues lately, I realized a need for a fall back value if the code couldn’t get anything. I also removed a variable declaration and then copied the returned value from the function to another variable, to hopefully optimize the code and make it work better and faster.

<?php

 // the function
 /**
 * @desc Get latest tweet from a Twitter account
 * @param string The account's username
 * @return string The tweet
 * http://www.phoenixheart.net/2009/05/code-snippet-1-get-latest-tweet/
 *
 */
 function get_latest_tweet($username) {
 $url = "http://search.twitter.com/search.atom?q=from:$username&rpp=1";
 $content = file_get_contents($url);
 $content = explode('<content type="html">', $content);
 $content = explode('</content>', $content[1]);
 return html_entity_decode($content[0]);
 }
 $my_tweet = get_latest_tweet('TWITTERLOGIN');
 if ($my_tweet == NULL)
 {
echo "Twitter is having issues again . . . .";
 }
 else {
 echo "$my_tweet";
 }

 ?>

Just paste this in a php file and change your twitter name so it gets the right feeds!