How to Create a Twitter Feed on Your Web Site
by c.bavota | Posted in Tutorials | 59 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.
$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.
$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.
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.
<?php
$username = "your-user-name";
$num = 5;
$feed = "http://search.twitter.com/search.json?q=from:" . $username . "&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.



I’ve placed a twitter feed widget in my sidebar (Magazine Basic). I’d like to add several twitter feeds in widget type format (a box) to the center column — not a sidebar. Is it possible to do that?
Thanks. You can see the twitter feed I have now on my site. I just want a page full of similar ones – each following its own feed.
Hello? Anyone?
Hey Osha,
You could use this code but it would need some modifications because of the file that is being copied over. If you just used it multiple times the files would overwrite themselves.
Hello.. this was my site up unitl a few moments ago..
http://moneyonline.affiliatemoneysite1.com
I need help, I somehow deleted my WP.org blog with the snowblind theme..in an attempt to get my twitter feed up and going..
AS I am reading your post on how easy this is.. please explain the word “easy” perhaps it is in your world. not mine..sorry about that I come from a different generation..
When you say in your post…
“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.”
Question…#1… I do know how to upload a file to my server, what I dont know is ….where and how do you create that file and what do you put in it to make it work right.
I apparently tried to edit the php within the editor and now this is all I get.
Warning: copy() [function.copy]: URL file-access is disabled in the server configuration in /homepages/26/d282906938/htdocs/WordPress2.8.2/wordpress/wp-content/themes/snowblind/widgets/widget_twitter.php on line 10
Warning: copy(http://search.twitter.com/search.thecoffeedude?q=from:&rpp=5) [function.copy]: failed to open stream: no suitable wrapper could be found in /homepages/26/d282906938/htdocs/WordPress2.8.2/wordpress/wp-content/themes/snowblind/widgets/widget_twitter.php on line 10
Question #2
Your theme is great dont get me wrong..I like it alot and I want to continue to use it..
but when you say it can edited, where and how do you do that????
I have been to the editor from my dashboard numerous times and in attempt to see a reaction to an action.. just for giggles to see what happens.. nothing happens..
I tried to change the username to my twitter username “thecoffeedude” within the editor and nothing changed.. then I deleted the entire php twitter tag code from the editor, updated the file, and guess what, the twitter bird still appeared on the my theme with no change at all..HUH!mmmmm
I then copied the php tag above from your post, inserted into the theme editor from my dashboard, inserted my username “thecoffeedude”
wherever I thought it needed to be and now I completely screwed it up big time. My blogsite doesn’t even appear at all.. just check out the link above and you’ll see.
In essence this little bird screwed me up completely..
Perhaps the best way to use the word easy.. must mean that its pretty easy to screw yourself up if you dont have the know how, this is obviously what you must mean..LOL HA HA..!
What I have concluded from this is that the editor within these themes is non responsive editor.
So now I assuming that these edit changes have to occur on the server but the server does not let you edit.. so whats the story here? Where do you edit, how do you create a file that works right so that I can load it onto my server..
For me to figure this out seems like an impossibility..
your use of the word “easy” HOLY COW… where did that ever come from…?????
this is far from easy..
Its more like a maze of executions.
its like the little mouse trying to get the cheese at the end of the maze..
I tend to think that this about about experience, something I dont have as of yet..Your right this isn’t really hard. We all know how to read, but many of us like myself dont know how to drive..
so thats why I need a little guidance from you, the designer of the snowblind theme..
Can you help me?
Thanks for listening..
Your server does not allow URL file access so the Twitter function will not work. Find a widget plugin to pull the Twitter feed and add it to the footer bar. That should solve the problem.
As for the above code being easy, it is if your server is configured properly. All you would have to do is cut and paste and change a few variables.
Hello.. Well after much inquiries and time from my hosting account who are always very helpful and responsive, we managed to restore the snowblind theme to its original status ..thank goodness..
However I would still like to know how to delete the 2 warning statements just below the STAY IN TUNE caption/tittle at the very bottom of the page..
the follow me twitter link apparently is working fine and it actually takes you to my twitter page.. great stuff.. how it does that, I have no idea.. I still would like to learn all about creating files and directories and editing in general..
As time will allow..
I do realize…Learning is ongoing experience..
Hope you can respond to me sometime, the earlier the better..
thanks.
RJR the coffeedude
Hey Ralph,
Some servers have higher security settings that make it very difficult to use certain code snippets and it seems like your server is one of them.
Can you suggest the perfect host for your theme..
If my hosting has high security settings..I rather switch than to try to change that.. not familiar..
thanks..
Bluehost is set up to work perfectly with my themes.
http://www.bluehost.com/track/odditycinema/
Hello Hello,
Really nice code, but it threw an error on line 23 – undefined variable, which I figured to be $limit. Just added $limit = 3; before the for loop and all worked fine.
Thanks!
Rob
Nice catch. Thanks. I have fixed the code above. You just needed to replace
limitwithnumI am using your feed with the Snowblind theme, things are working great except that the shortened hyperlinks are not functioning properly. Any help would be really appreciated…
Can people really make money on Twitter? I have been reading this web site that says people can.
Yep! You can post some aff codes with an url shortener!
I have been working on my Twitter followers, trying to build them up. Is this worthwhile down the road if I want to make money by marketing to them?
Pretty great! It´s working fine. Thx for share.
Amazing!! Thank you sooo much
Remember CHMOD the .json directory to 777
Getting an error.
Deprecated: Function ereg_replace() is deprecated in line 30
which is this line.
$str = ereg_replace(“[[:alpha:]]+://[^[:space:]]+[[:alnum:]/]”,”\“, $tweets->results[$x]->text);
I’am really just starting PHP so I really don’t know what’s happening. Using WAMP Sever2.0 to test it. Anybody know what went wrong?
It is deprecated as of PHP 5.3 and will be removed in PHP 6. They suggest using PCRE extension instead.
Changed ereg_place with str_replace and this seemed to work.
Hello, I am a bit confused regarding what I should write in place of __FILE__. Is this the place where I want the file to be copied?
Could you show me a practical example?
Never mind, I figured out by myself.
I was doing everything right, but apparently only the latest messages are retrieved this way – and setting the since_id parameter does nothign at all… has anyone had the same problem?
For some reason, Twitter only shows the messages from the past seven days or so. You will notice in my footer that every once in a while the five Tweets become only two or three. Weird but that is how they do it. I guess it is a reason to Tweet more.
Firstly, I love the code, but I’m looking to just go a little further. Can you use the json return file to show the post date/time? i.e. to display under each li “about X mins/hours/days ago”
There is a way but my math skills are a little rusty and it requires taking the posting date/time and the current date/time and doing a bunch of funky things to it.
Youve lost me with the .Json file????
Where do i get it? Where do i put it?
The .json file is taken from Twitter using the API. The code above copies it. You might want to try the other Twitter feed tutorial I have.
http://bavotasan.com/tutorials/a-better-twitter-feed-for-your-web-site/
Hello,
I’m not a PHP expert so I have a few questions after putting the .json file into php tags. Where do I go from there, do I connect the php file to the index page? Or does it automatically connect to the index page?
Thanks heaps! Works a treat.
Wondering though…how could the code be affected to not display retweets?
Hit me up directly if you’d prefer.
All help appreciated.
Hmm. Not that I know of. But you can look through the Twitter API and see if it is at all possible.
http://apiwiki.twitter.com/Twitter-API-Documentation
Hi,
Does this display all latest tweets from all friends in your twitter account or just tweets by myself ?
Thanks
This will only display your tweets and direct messages. You can check out the Twitter API to see how you can modify the request.
http://apiwiki.twitter.com/
Hi I am having an error on
Notice: Undefined offset: 0 in c:\easyphp1-8\www\test\facebook-twiiter\json\index.php on line 25
for($x=0;$x<$num;$x++) {
$str = ereg_replace("[[:alpha:]]+://[^[:space:]]+[[:alnum:]/]”,”\“, $tweets->results[$x]->text);
$pattern = ‘/[#|@][^\s]*/’;
preg_match_all($pattern, $str, $matches);
Hi really need your help badly..