Posts Tagged ‘Twitter’

We all know how annoying it is to not have any customization with the ways Twitter provides to show your latest Tweet. We all also know how annoying it is that your server lags out if the Twitter service is down when using the ways they provide. The obvious alternative method is to use the Twitter API to pull out your latest tweet, but that could cause more problems than it fixes, especially if you are requesting information from the server too much.

So, what’s the alternative? RSS. Twitter generates a dynamic feed that allows parameters to be set to limit the results. (Documentation on Formats from Twitter.) For example, here is a feed showing results for my account: http://search.twitter.com/search.atom?q=from:RyanBarr. Notice how my username can be seen from the URL.

Problem here is we are only looking for the latest tweet, so we will use the rpp parameter Twitter has made for us to limit our results to a single tweet

Pretty boring, right? That’s what I expected and exactly why I have found the following script to make it easy for everyone to implement on the fly:

<?php

// Your twitter username.
$username = "TwitterUsername";

// Prefix - some text you want displayed before your latest tweet.
// (HTML is OK, but be sure to escape quotes with backslashes: for example href=\"link.html\")
$prefix = "";

// Suffix - some text you want display after your latest tweet. (Same rules as the prefix.)
$suffix = "";

$feed = "http://search.twitter.com/search.atom?q=from:" . $username . "&rpp=1";

function parse_feed($feed) {

$stepOne = explode("<content type=\"html\">", $feed);
$stepTwo = explode("</content>", $stepOne[1]);

$tweet = $stepTwo[0];
$tweet = str_replace("&lt;", "<", $tweet);
$tweet = str_replace("&gt;", ">", $tweet);

return $tweet;

}

$twitterFeed = file_get_contents($feed);

echo stripslashes($prefix) . parse_feed($twitterFeed) . stripslashes($suffix);

?>

You will need to update the $username variable to hold your Twitter username. You will need to be running PHP on the server and the file extension must be .php (unless you are using .htaccess to treat .html files as PHP). Other than that, wherever you place this code on your page is where the information is output. (Have basic PHP knowledge? Try moving this script to a header file and populating a variable that gets displayed later on.)

As this is part one of a four part series there are a few things to understand:

  • The script above only pulls the latest tweet from the RSS, no timestamps or other information.
  • The script is pulling from a file on the Twitter servers, so you are still depending on that file being active.
  • As this script is pulling from an outside file, you still might experience some delay. Though the delay exists, it isn’t much a difference from the Javascript method that is currently available.

Courtesy:http://scriptplayground.com/tutorials/php/Latest-Twitter-Update-With-PHP/