How to display your latest tweet with PHP

Posted on Friday 1st Oct 2010 by James Bavington 27 Comments

Display latest tweet with PHP (v2)

One of our most popular video blogs from earlier this year – was our free PHP script that allows you to display your latest Tweet on your website. Since we published the script we’ve had a lot of requests to add additional features such as displaying more than one tweet, and also showing how long ago the tweets were.

Check out the example from the video.

So taking on all the feature requests, we have developed a new script from scratch that gives you all of the control you should need for displaying tweets on your web design without the help of any intrusive Twitter widgets. In our original script, all that it could do was quite simply grab the very latest tweet and convert it to HTML.

In Version 2 – you can now:

  • Choose how many tweets you would like to display.
  • Accompany them with how long ago they were tweeted.
  • Choose to allow HTML to filter through, or Strip the tags so that they don’t contain any links.
  • Add ‘nofollow ‘and ‘target blank’ attributes to any links contained within the tweet.

To install the script on your website, you have two options. You can either download the example from the video, or you can copy and paste the two scripts from below.

Part 1 – The PHP Script

To make the script easier to install, we have broken it into two parts. First of all, copy the following PHP script. Then create a new PHP page on the root layer of your website (or wherever you wish to store it) and name the file ‘latest-tweet.php’.

<?php

 function changeLink($string, $tags=false, $nofollow, $target){
  if($tags){
   $string = strip_tags($string);
  } else {
   if($target){
    $string = str_replace("<a", "<a target=\"_blank\"", $string);
   }
   if($nofollow){
    $string = str_replace("<a", "<a rel=\"nofollow\"", $string);
   }
  }
  return $string;
 }

 function getLatestTweet($xml, $tags=false, $nofollow=true, $target=true){

  $xmlDoc = new DOMDocument();
  $xmlDoc->load($xml);

  $x = $xmlDoc->getElementsByTagName("entry"); // get all entries

  $tweets = array();
  foreach($x as $item){
   $tweet = array();

   if($item->childNodes->length)
   {
    foreach($item->childNodes as $i){
     $tweet[$i->nodeName] = $i->nodeValue;
    }
   }
    $tweets[] = $tweet;
  }

  // if using bullets start UL here
   echo "<ul>\n";

  foreach($tweets as $tweettag){
   /********************** Getting Times (Hours/Minutes/Days) */
   $tweetdate = $tweettag["published"];
   $tweet = $tweettag["content"];
   $timedate = explode("T",$tweetdate);
   $date = $timedate[0];
   $time = substr($timedate[1],0, -1);
   $tweettime = (strtotime($date." ".$time))+3600; // This is the value of the time difference - UK + 1 hours (3600 seconds)
   $nowtime = time();
   $timeago = ($nowtime-$tweettime);
   $thehours = floor($timeago/3600);
   $theminutes = floor($timeago/60);
   $thedays = floor($timeago/86400);
   /********************* Checking the times and returning correct value */
   if($theminutes < 60){
    if($theminutes < 1){
     $timemessage =  "Less than 1 minute ago";
    } else if($theminutes == 1) {
     $timemessage = $theminutes." minute ago.";
     } else {
     $timemessage = $theminutes." minutes ago.";
     }
    } else if($theminutes > 60 && $thedays < 1){
     if($thehours == 1){
     $timemessage = $thehours." hour ago.";
     } else {
     $timemessage = $thehours." hours ago.";
     }
    } else {
     if($thedays == 1){
     $timemessage = $thedays." day ago.";
     } else {
     $timemessage = $thedays." days ago.";
     }
    }
    echo "<li>".changeLink($tweet, $tags, $nofollow, $target)."<br />\n";
    echo "<span>".$timemessage."</span></li>\n";
   }

    echo "</ul>\n";
   // if using bullets end UL here
 }

 // Usage (XML FEED, STRIP_TAGS (DEFAULT NO), NOFOLLOW (DEFAULT YES), TARGETBLANK (DEFAULT YES))
 $tweetxml = "http://search.twitter.com/search.atom?q=from:" . $twitterid . "&rpp=" . $numberoftweets . "";

 ?>

Part 2 – Enabling and customising PHP Script

Now that you have the PHP script stored on your server, you need to call it and customise it. Open the page or template where you want to embed the latest tweet. Paste in the code below.

Next you need to customise the settings within this file. Start by changing the twitterid variable from ‘crearegroup’ to your Twitter user-name. Next change the ‘numberoftweets’ variable from 4 to the number of tweets that you wish to display. The next thing to do is ensure that you have sourced the PHP script correctly in Step 3. If you have stored the script in a folder, simply update the path accordingly.

Finally, you have the option to adjust the new features included within this script. By default, HTML tags are not stripped, and links will include the ‘rel=nofollow’ and ‘target= _blank”‘ attributes.

<?php
// Step 1 - Swap crearegroup for your Twitter User-name
$twitterid = "crearegroup";
// Step 2 - How many tweets to you want to show? Swap 4 for how many you would like.
$numberoftweets = "4";
// Step 3 - Make sure that you source the include file correctly below:
require_once('latest-tweet.php');
// Step 4 - Usage (XML FEED, STRIP_TAGS (DEFAULT NO), NOFOLLOW (DEFAULT YES), TARGETBLANK (DEFAULT YES))
getLatestTweet($tweetxml, false, true, true);
 ?>

By default, the above script echoes the tweets in an unordered list. If you wish to change this to paragraph tags or something else, simply open the latest-tweet.php script and customise accordingly.

About James Bavington

Away from computers, James enjoys mountains, military history and has an insatiable appetite for film - particularly 90's classics.

See all of posts.

Add on James Bavington Google+

James Bavington's Tweet's

This entry was posted in Web Design Videos and tagged , . Bookmark the permalink.

27 Responses to How to display your latest tweet with PHP

  1. Andrew says:
    October 14, 2010 at 2:40 am

    Just wanted to say THANK YOU! This worked IMMEDIATELY and I love the level of configuration. Great stuff.

  2. Khriz says:
    October 19, 2010 at 8:39 pm

    Problem with special chars. I use all my sites in ISO-8859-1

  3. Tom says:
    October 27, 2010 at 4:05 pm

    Thanks for this it was working a treat. Unfortunately it’s stopped working and I can only assume it’s because I’ve hit the twitter API call limit, which I was unaware of before.

    Is this not something that’s happened to you, or am I doing something wrong? Is there a way of caching the query, so it will only update once an hour?

  4. James Bavington says:
    October 28, 2010 at 7:45 am

    Hey Tom, indeed the script is reliant on Twitter supplying the feed. Particularly if your Twitter account is busy, it can suppress your feed. We are already working on a 3rd version of the script that stores the previous tweet information, in the event of the API call limit being reached.

  5. Tom says:
    October 28, 2010 at 12:44 pm

    Good to know. It seems that the reason it wasn’t working was nothing to do with the call limit and simply because the twitter feed I was linking to hadn’t been updated for over a week!

  6. James Bavington says:
    October 28, 2010 at 12:54 pm

    Hey Tom, that’s also another good point that I forgot to mention in the video. If no new tweets appear (usually after 3-5 days) the feed stops, to free up resource for those using their accounts. If you add a tweet at least every other day, the feed stays stable.

  7. Andy Carne says:
    November 2, 2010 at 9:09 pm

    Hi this is a great tutorial, and it appears to be working well for several people so its nothing to do with the script, but i just cant get anything out of it on a site Im trying it with…just blank…, even by downloading your folder exactly as is and dropping it on my site with no adjustments?

    Your example on your site works fine on my browser but when hosted on my site, no tweet :(

    The webspace is PHP enabled and hosted by Rackspace

    Any ideas what might be missing?

    A

  8. henk says:
    November 13, 2010 at 9:50 am

    Hello,

    still trying, but i experience the same problem as Andy. When i copy your example to my own site, i only see the twitter bird…

    t.i.a. henk.

  9. Jamie Harvey says:
    November 25, 2010 at 11:36 am

    I have the same problem as Andy and Henk. I can get intro and ending text to display but no tweets – it’s just blank. Any idea what could be wrong?

  10. Ben Stanley says:
    November 25, 2010 at 11:57 am

    On the site I am making I am using this script and it is working well except for the timestamp. It always says Less than 1 minute ago…

    Where you have the code:
    $tweettime = (strtotime($date.” “.$time))+3600

    Do I change it to my local time (GMT+12)?

    So the code would be:
    $tweettime = (strtotime($date.” “.$time))+43200

    Thanks
    Ben

  11. Daniël Voogsgerd says:
    November 25, 2010 at 8:17 pm

    @Ben Stanley
    I think your problem is that the server isn’t set to the right timezone the problem can be solved by changing

    $nowtime = time();
    into
    $nowtime = gmmktime();

    and

    $tweettime = (strtotime($date.” “.$time))+3600;
    into
    $tweettime = strtotime($date.” “.$time);

  12. Ben Stanley says:
    November 26, 2010 at 12:48 am

    When I test the twitter feed locally (localhost) the correct Tweet time shows (e.g 13 hours ago) but when it is on the server it always says “Less than 1 minute ago”. Do you have any idea why this would happen. I copied the complete site from my computer to the server and it still said Less than 1 minute ago after saying 13 hours ago in localhost… It’s weird…

  13. rob says:
    November 26, 2010 at 9:02 am

    Hi Guys,

    Just wanted to let you know that you will need PHP5 to use this script to its limit. Those of you whose tweets are not displaying is probably due to the Read XML function not functioning on PHP4 or lower.

    I’ll see if I can drum up a PHP4 version of this script with a different XML parser.

    As for the server time – yes that example was hosted on a web server with GMT-1 to get it to generate UK time I needed to add an hour to the time generated by the server.

  14. Daniël Voogsgerd says:
    November 26, 2010 at 3:44 pm

    @Ben Stanley
    The cause of your problem is the timezone which your computer uses probably your server. This problem can be solved by using GTM as timezone for your generated time. The “tweettime” is also in GTM so you won’t need to add extra seconds to the time. See my previous comment for the changes you will have to make to get it working.

    And about the php4 and earlier problem, I’ve got a twitter script for myself using CURL and json. If you want to use/try that version, you can find the script and demo below

    Script: http://www.realiseweb.nl/examples/twitter/script.txt
    Demo: http://www.realiseweb.nl/examples/twitter/demo.php

  15. Daniël Voogsgerd says:
    November 26, 2010 at 3:48 pm

    I had forgotten to say that the script automatically caches the tweet. You’re able to set the Cache lifetime to anything you want.

  16. Andy Carne says:
    November 29, 2010 at 5:10 pm

    Hi Rob, thanks for the update but my site is PHP5 enabled…any other ideas? A

  17. Bjorn says:
    March 1, 2011 at 9:16 pm

    This is the most simple, but best script I found for displaying twitter without the widgets I don’t like.
    The comments of Daniël are very useful, because I hade the same issue before.
    But still, I’m having a little stupid problem: In FF it works flawless, but in IE the ‘ is displayed as ' and i can’t figure out how to solve it. Maybe anyone can help me out?

  18. Nilesh says:
    July 17, 2011 at 10:45 pm

    hi there, i was making some change with your twitter coding to add to my website and noctice when i was validating with w3c that the code does not support stict xhtml 1.0 due to the target attribute. is there something that i can change so that it support strict xhtml?

  19. udajon says:
    July 20, 2011 at 9:15 am

    thank you for your tutorial and script i have tried and success…

  20. Mark Syred says:
    August 29, 2011 at 10:10 am

    This is fab. Updates the tweet immediately. Had used js but, wasn’t happy that it didn’t alter the html. As this does, am very happy. Cheers.

  21. noush says:
    September 22, 2011 at 3:24 pm

    how to display time separately let say tweet msg in a box and 2 hour ago in a 2nd box

  22. Marco Loreto says:
    September 22, 2011 at 9:14 pm

    Hi! Congratulations and thank you for an excellent script, i was wondering. Is it possible to only show one tweet at a time, that refreshes every certain amount of time? Thank you in advance

  23. jacob says:
    September 30, 2011 at 5:37 pm

    works like charm perfect!

  24. Dan says:
    November 14, 2011 at 10:55 pm

    First thanks for taking the time to inform us who seek to post our tweets on our own websites. For me I had an error message. I posted all the raw files (from the downloadable zip file from this blog) on my web-host and receive the following error message: Fatal error: Call to undefined method: domdocument->load() in /*/*/latest-tweet.php on line 20. Going over the code in the ‘latest-tweet.php’ file it refers to the $xmlDoc calls.

    …any input would be greatly appreciated. Thanks again!

  25. Dan says:
    November 15, 2011 at 6:56 am

    Dan here again. Just wanted to post a resolution to the previous problem I posted in the case that someone else might have the same problem. It is a web hosting issue, specifically with the php.ini file that I as a client would not have access to on shared hosting (1&1, avoid them if you’re a developer on any level). I tested the same code on another hosting account (different company) and it worked perfect. – Regards

  26. Christiaan Hendriksen says:
    December 1, 2011 at 10:49 pm

    Is there any way to filter tweets containing a certain hashtag?

  27. SamMclain says:
    January 3, 2012 at 5:37 pm

    hello Jame’s i do this and paste the code on mamp but its have a bug? why

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>