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);
?>



Just wanted to say THANK YOU! This worked IMMEDIATELY and I love the level of configuration. Great stuff.
Problem with special chars. I use all my sites in ISO-8859-1
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?
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.
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!
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.
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
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.
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?
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
@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);
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…
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.
@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
I had forgotten to say that the script automatically caches the tweet. You’re able to set the Cache lifetime to anything you want.
Hi Rob, thanks for the update but my site is PHP5 enabled…any other ideas? A
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?
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?
thank you for your tutorial and script i have tried and success…
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.
how to display time separately let say tweet msg in a box and 2 hour ago in a 2nd box
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
works like charm perfect!
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!
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
Is there any way to filter tweets containing a certain hashtag?
hello Jame’s i do this and paste the code on mamp but its have a bug? why
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.
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);
thanks for this postS
it really helps me
i have problem with twitter about this