Web Design Tutorial – How to display your latest tweet with PHP

Posted on Friday 17th Feb 2012 by James Bavington 30 Comments

Click here to see and download the example from the video

In this week’s web design video we’re launching version 3 of our popular PHP Script that displays your latest tweets on your website.  Twitter themselves  do of course offer their own customizable widgets for displaying tweets, however these are limiting from a design perspective and not that accessible to search engine bots looking for fresh content.

Put simply, our PHP Script fetches your latest tweets in real-time and displays them as simple HTML on your web pages. In version two last year – we added the ability to activate links within the tweets, show more than one tweet, and also provide an accompanying timestamp of how long ago each tweet was.

What’s new in Version 3 of PHP Latest Tweet?

In version three we’ve added several new features that allow you choose:

  • whether to target blank the links
  • nofollow the links for SEO purposes
  • also an optional Twitter follow button
  • Easier Installation

The PHP Code from the video.

Simply copy and paste all of the code onto your PHP5 web page, and customise the various steps.

<?php
	// Step 1 - Swap crearegroup for your Twitter User-name
	$twitterid = "jamesbavington";

	// Step 2 - How many tweets to you want to show? Swap 4 for how many you would like.
	$numberoftweets = "5";

	// Step 3 - Would you like to activate links within the tweets?
	$tags = true;

	// Step 4 - Would you like to activate nofollow (Best for SEO)?
	$nofollow = true;

	// Step 5 - Would you like links to appear in a new window/tab?
	$target = true;

	// Step 6 - Would you like to show the Twitter Follow Widget button?
	$widget = true;

	// Here's the Science - futher comments can be found below
	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,$widget=false){
		global $twitterid;
	  $xmlDoc = new DOMDocument();
	  $xmlDoc->load($xml);

	  $x = $xmlDoc->getElementsByTagName("entry"); 

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

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

	// Here's the opening DIV and List Tags.
	   echo "<div id=\"latesttweet\"><ul>\n";

	  foreach($tweets as $tweettag){
	   $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);
	   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.";
		 }
		}
		// Here's the list tags wrapping each tweet.
		echo "<li>".changeLink($tweet, $tags, $nofollow, $target)."<br />\n";
		// Here's the span wrapping the time stamp.
		echo "<span>".$timemessage."</span></li>\n";
	   }
	// Here's the closing DIV and List Tags.
		echo "</ul></div>";

		// Here's the Twitter Follow Button Widget
		if($widget){
			echo "<a href=\"https://twitter.com/" .$twitterid. "\" class=\"twitter-follow-button\" data-show-count=\"true\">Follow @" .$twitterid. "</a>
		<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=\"//platform.twitter.com/widgets.js\";fjs.parentNode.insertBefore(js,fjs);}}(document,\"script\",\"twitter-wjs\");</script>";
		}

	 }
		$tweetxml = "http://search.twitter.com/search.atom?q=from:" . $twitterid . "&rpp=" . $numberoftweets . "";
		getLatestTweet($tweetxml, $tags, $nofollow, $target, $widget);
 ?>

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

  • RT @WarwickADavis: A man called 'Alan Smith' phoned from India. He told me my Microsoft PC was about to 'die'. He wanted access to fix. I own an iMac! #scam 5 hours ago.
  • RT @JustSearch: Looks like Google's homepage now has a share box for #GooglePlus. There's no getting away from it now. 1 day ago.
This entry was posted in PHP Scripts & Tutorials, Web Design Videos and tagged , . Bookmark the permalink.

30 Responses to Web Design Tutorial – 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

  28. Anthony Luxton says:
    February 17, 2012 at 5:39 pm

    Hey, thanks for your article. I noticed you said you were working on caching of the XML feed. I thought I would share something I knocked up quickly which caches the feed for an hour at a time. Simply replace the first two lines of code within the getLatestTweet function with the following:


    $fname = 'twitter.xml';
    $xml_string = false;
    if(file_exists($fname)) {
    if(filemtime($fname) loadXML($xml_string);

    Perhaps people will find this useful until you update your script to support this.

    Good work.

  29. Anthony Luxton says:
    February 17, 2012 at 5:46 pm

    Sorry my recent comment’s less-than tags weren’t handled very gracefully which has chopped the code in half.

    Second time lucky…

    $fname = 'twitter.xml';
    $xml_string = false;
    if(file_exists($fname)) {
    if(filemtime($fname) < strtotime("+ 1 hour")) $xml_string = file_get_contents($fname);
    }
    if($xml_string === false) {
    $xml_string = file_get_contents($xml);
    $fh = fopen($fname,'w');
    fwrite($fh,$xml_string);
    fclose($fh);
    }

    $xmlDoc = new DOMDocument();
    $xmlDoc->loadXML($xml_string);

  30. هتل says:
    February 18, 2012 at 7:37 pm

    thanks for this postS
    it really helps me
    i have problem with twitter about this

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>