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:

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:

Photo by ~basia-hs

  • Justin

    I’ve been trying to use your code (thanks for posting it) to create an archive of search results. I tried replacing the url being set to $buffer to:
    “http://search.twitter.com/search?q=search-term” but get ‘String could not be parsed as XML.’ I’ve been trying to figure out what the difference in results between a normal Twitter feed and the Twitter search is, and if you might have any ideas as how to resolve this.
    Thanks for any help you can provide.
    Justin

  • Stathis

    Hello Justin.

    The url format of the Twitter Search API Method is:
    http://search.twitter.com/search.format?q=query

    The available formats are json and atom. I’m gonna use atom for the following example:

    $twitter_url = ‘http://search.twitter.com/search.atom?q=burnmind’;
    $buffer = file_get_contents($twitter_url);
    $xml = new SimpleXMLElement($buffer);
    $entry = $xml -> entry;
    $title = $entry -> title;

    Using this code you’ll get the the title of the first search result for the term “burnmind” in the $title variable.

    If you want to see which other data fields you can use, execute the search url in your web browser and take a look at the source code of the resulted atom feed.

    I hope this helps!