how to retrieve and display your latest tweet using PHP

Twitter 5 by jasonh1234 on deviantART

Retrieving your latest tweet from twitter is a very simple process. First, you need to request your latest tweet from twitter using its API and then parse the xml response and select your tweet. It’s much simpler than it sounds!

You can request your latest tweet from twitter just by using a simple URL: By replacing YourUserName with your twitter username, you’ll get an xml file containing your latest tweet (you can request more tweets by changing the “count=1” with the appropriate number of tweets) along with some information about your profile.

Using the following PHP code, you’ll get the content of the xml response to the $buffer variable:

$twitter_url = '';
$buffer = file_get_contents($twitter_url);

Now that you have the xml content, you just need to parse it so you can retrieve your tweet. Using SimpleXML, which is a PHP extension that allows users to easily manipulate/use XML data, the content is converted to a set of nodes. The $status variable holds the “status” node and then the $tweet variable gets the child-node named text, which is your tweet. Finally, the tweet is displayed using the echo command.

$xml = new SimpleXMLElement($buffer);
$status = $xml -> status;
$tweet =  $status -> text;
echo $tweet;

Simple, right?

You can also use an alternative way: how to store and retrieve your latest tweet from an XML file

Creation by ~jasonh1234