how to store and retrieve your latest tweet from an XML file

felt twitter bird by basia-hs on deviantART

Retrieving and displaying a tweet using the twitter API in real-time as discussed in “how to retrieve and display your latest tweet using PHP” can sometimes produce errors due to twitter’s inability to handle a lot of simultaneous request from multiple users. To deal with that, you can store the tweet in an XML file and retrieve it from there, so you don’t have to rely on twitter’s availability. This way is more efficient and will improve the loading time of the page.

First, you need to create a file named loadtweet.php which will load the latest tweet the usual way, will perform a check to find out if the result is an actual tweet and not an error message by computing the tweet’s length (it must have a maximum length of 140 characters) and will finally save the whole respond to an XML file called tweet.xml:

$twitter_url = 'http://twitter.com/statuses/user_timeline/yourTwitterUserName.xml?count=1';
$buffer = file_get_contents($twitter_url);

$xml = new SimpleXMLElement($buffer);
$status_item = $xml -> status;
$status =  $status_item -> text;
$length = strlen($status);

if ($length < 141)
{
$file = fopen("tweet.xml", "w");
fwrite($file, $buffer);
fclose($file);
}

Your Web Server can be scheduled to execute this file automatically, for example every one minute, using a Cron Job (reffer to your Web Server’s Control Panel or your Hosting Company to find out how to schedule a Cron Job).

To retrieve the tweet from the XML file and display it wherever you want in your page, use the following code:

$xml = simplexml_load_file("tweet.xml");
$status_item = $xml -> status;
$status =  $status_item -> text;
echo $status;

Photo by ~basia-hs