TutorialsWeb Design

UPDATE – I have posted a more recent ‘part two’ post which uses SimplePie to retrieve your Tweets. Check out the post: Tutorial: Display your Latest Tweet on your Website using SimplePie

You will have noticed that I display my latest Tweet in the header of my website (look up). Until recently I have been using the Twitter for WordPress plug-in, but I was experiencing problems and 9/10 times my page loaded I would get the error message instead on my Tweet! This became increasingly frustrating, as my site would get featured on someone else’s blog and the screenshot would contain this error message. After persevering with this plugin and contacting the author, I came to the conclusion I need to look elsewere.

Anyway, less of the chatter Stu! Here’s the code….

$username = “TwitterUsername”; // Your twitter username.
$prefix = “”; // Prefix – some text you want displayed before your latest tweet.
$suffix = “”; // Suffix – some text you want display after your latest tweet.
$feed = “https://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);

Make sure you change the ‘TwitterUsername‘ to your own Twitter Username. If you want to keep your code clean, then you can move this script into your header tags, but you will need to change this line:

[php light=”true”]
echo stripslashes($prefix) . parse_feed($twitterFeed) . stripslashes($suffix);

to this:

[php light=”true”]
$tweet = stripslashes($prefix) . parse_feed($twitterFeed) . stripslashes($suffix);

Then you can just call this variable later on in your code where you want your Tweet to be displayed. Finally, I just want to mention that if you come across the following error:

Warning: file_get_contents(): URL file-access is disabled

You will need to do one of the following:

  • Edit your PHP.ini file (usually located in /etc/php.ini) and make sure this line is in it:
    allow_url_fopen = On
  • Create a file called “.htaccess” in your website root directory with the following line:
    php_value allow_url_fopen on

This should sort out the problem, but if you need any more help then leave a comment and I will gladly help! If the whole process went smoothly, then you should be appreciating your Latest Tweet on your website just like me!