Oct
07
2009

How to Create a Twitter Feed on Your Web Site

by   |  Posted in Tutorials  |  54 comments

Twitter has quickly become one of the most popular social networking sites online. It is currently ranked among the top twenty Web sites in the world and has over a million users. I have only recently hopped on the bandwagon and so far I have been able to connect with many interesting people and discover tons of great online resources. I added a Twitter feed into my footer once I got things going and I have been refining the code ever since. I finally have it at a point where I think all of the bugs are ironed out and it is ready to share.

The Twitter API is pretty easy to use and I decided to work with the Search API Method. I found that sometimes Twitter doesn’t respond due to high traffic on the site so instead of just using the API to return an Atom Feed, I decided to use is to return a Json file.

First, let’s setup our username and the number of Tweets we want to display.

1
2
3
4
$username = "your-user-name";
$num = 5;
 
$feed = "http://search.twitter.com/search.json?q=from:" . $username . "&rpp=" . $num;

Next we need to copy the Json file to our server, just in case the Search API doesn’t respond during our next attempt to grap our Tweets.

5
6
7
8
9
10
11
12
13
14
15
16
17
18
$newfile = dirname(__FILE__)."/twitternew.json";
$file = dirname(__FILE__)."/twitter.json";
 
copy($feed, $newfile);
 
$oldcontent = @file_get_contents($file);
$newcontent = @file_get_contents($newfile);
 
if($oldcontent != $newcontent) {
copy($newfile, $file);
}
$tweets = @file_get_contents($file);
 
$tweets = json_decode($tweets);

This will also check to see if any new Tweets have been added before it attempts to copy over the new Json file.

To finish it all off, we need to display our Tweets. This examples outputs them into an unordered list.

19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
echo "<ul>";
for($x=0;$x<$num;$x++) {
$str = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href=\"\\0\">\\0</a>", $tweets->results[$x]->text);
$pattern = '/[#|@][^\s]*/';
preg_match_all($pattern, $str, $matches);	
 
foreach($matches[0] as $keyword) {
$keyword = str_replace(")","",$keyword);
$link = str_replace("#","%23",$keyword);
$link = str_replace("@","",$keyword);
if(strstr($keyword,"@")) {
$search = "<a href=\"http://twitter.com/$link\">$keyword</a>";
} else {
$link = urlencode($link);
$search = "<a href=\"http://twitter.com/#search?q=$link\" class=\"grey\">$keyword</a>";
}
$str = str_replace($keyword, $search, $str);
}
 
echo "<li>".$str."</li>\n";
}
echo "</ul>";

Let’s put it all together and wrap it in a PHP tag.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
$username = "your-user-name";
$num = 5;
 
$feed = "http://search.twitter.com/search.json?q=from:" . $username . "&amp;rpp=" . $num;
 
$newfile = dirname(__FILE__)."/twitternew.json";
$file = dirname(__FILE__)."/twitter.json";
 
copy($feed, $newfile);
 
$oldcontent = @file_get_contents($file);
$newcontent = @file_get_contents($newfile);
 
if($oldcontent != $newcontent) {
copy($newfile, $file);
}
$tweets = @file_get_contents($file);
 
$tweets = json_decode($tweets);
 
echo "<ul>";
for($x=0;$x<$num;$x++) {
$str = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href=\"\\0\">\\0</a>", $tweets->results[$x]->text);
$pattern = '/[#|@][^\s]*/';
preg_match_all($pattern, $str, $matches);	
 
foreach($matches[0] as $keyword) {
$keyword = str_replace(")","",$keyword);
$link = str_replace("#","%23",$keyword);
$link = str_replace("@","",$keyword);
if(strstr($keyword,"@")) {
$search = "<a href=\"http://twitter.com/$link\">$keyword</a>";
} else {
$link = urlencode($link);
$search = "<a href=\"http://twitter.com/#search?q=$link\" class=\"grey\">$keyword</a>";
}
$str = str_replace($keyword, $search, $str);
}
 
echo "<li>".$str."</li>\n";
}
echo "</ul>";
?>

To see this script in action, just check out my footer.

Twitter Bird image provided by Pasquale D’Silva and Function.

About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
Share the love...

Tags: , , , , , , , , , , ,

Short URL: http://bit.ly/dj7sk5

Discussion 54 Comments

  1. Josh Stevens on October 4, 2010 at 12:39 am

    Hi,
    I really want to get this working but all i end up with is 5 dots form the unordered list (ive turned off the css to see what the problem is).
    Ive basically straight copy and pasted your last code box which has the completed PHP code, made a new PHP file and changed the twitter username to my username.
    Any ideas what could be wrong here?
    thanks

  2. Tom on October 28, 2010 at 7:10 am

    Thanks for this, it seems to work very well. I was concerned that there was no way to limit the amount of calls to the twitter API. I have modified the script slightly as below:

    $newfile = dirname(__FILE__)."/twitternew.json";
    $file = dirname(__FILE__)."/twitter.json";
     
    $modtime = filemtime("twitter.jason");
    $curtime = time();
     
    if ($modtime + 60 &lt;= $curtime) {
    copy($feed, $newfile);
    }
     
    $oldcontent = @file_get_contents($file);
    $newcontent = @file_get_contents($newfile);

    It seems to be working, but I’m new to PHP, so if I’ve made an error, let me know!

    • c.bavota on October 28, 2010 at 8:34 am

      Just note that it is json and not jason like you have it above.

    • Tom on November 1, 2010 at 6:51 am

      Well spotted, thanks very much.

  3. MyShadowSelf on November 4, 2010 at 7:10 am

    Excellent, just what I was looking for. Great idea to cache the response, saves on lots of errors when twitter.com (invariably) goes down.

    Cheers

  4. Jase on November 12, 2010 at 8:53 am

    Pukka! It worked for me – I tried a few and even managed to customise slightly.

    Were some conflicts though initially.

  5. blog set up on February 17, 2011 at 11:27 am

    That’s going above my head :) Don’t we have a plugin?

    • c.bavota on February 18, 2011 at 10:13 am

      There are some plugins out there. I just prefer to hard code some stuff myself. It gives me more control and understanding of how WordPress and this extra functionality works.

  6. Paul Burnhill on April 15, 2011 at 6:04 am

    Great tutorial, thank you. I have it all working great apart from the fact it seems to put a colon after any @links in the feed. This causes issues when people click them as twitter can’t find “@name:”

    As no one else seems to have this trouble, I’m not sure what’s going on. Does anyone have any suggestions?

    • Paul Burnhill on April 15, 2011 at 6:43 am

      Ah sorry, I just realised the twitter feed I was testing with was basically all retweets – hence all the colons.

      Nothing to see here – move along!