
I’m not a Twitter user myself, but displaying your latest Twitter updates (or tweets) somewhere on your blog or website has increasingly become popular. And since I’ve written a pure PHP RSS2.0 feed parser earlier, I decided to try writing one targeted at Twitter. As always I’m always looking for the simplest solution which requires as little additional software, scripts or external libraries as possible, preferably none if this is at all possible. After some digging and modifying my existing basic RSS feed parser, I’ve written, and now sharing, a pure PHP code which retrieves and displays your tweets. You only need your Twitter username and PHP (version 4 and up I believe).
This is meant as a tutorial for someone who is looking for something just as simple as this, or a pointer for someone who is wish to write a complex feed parser for social medias. It’s targeted at people who know and understand some PHP beforehand. This code is as simple as it gets, including only the absolutely necessary things. This excludes for example error handling. I would also prefer that you read through and write it out yourself, not just copy-paste it. If you write it out yourself you can customize it to your liking, and you learn much more.
I find it suitable to mention that Twitter offers a service for displaying tweets on your blog or site by using Twitter badges. It’s free, very customizable and requires much less code, and may be just the thing you need. It updates dynamically, but requires JavaScript. I wanted full control, and I was also curious whether I could or not make a feed parser that retrieves roughly the similar information as Twitter’s badges using PHP only. So, let’s get started.
PHP function to fetch tweets
I’ve put the fetching code nicely inside a function which you can place where you want it, in the beginning of your site’s files or in, if you have, your function.php file. The function takes two arguments (the twitter user name as string and the number of tweets as integer) and have not got any error handling code for e.g. checking the validity or type of arguments. So be sure you got the arguments right, or write an error handling code yourself.
I extract the description and pubDate fields only, but you can add more fields if you like. This code uses regular expressions to convert hyperlinks (http://), links to Twitter users (@) and hash tags (#) that may appear in the tweet. In addition, because I live in Norway and we have special signs in our language this code also converts the tweets into ISO-8859-1 so non-English tweets don’t get funny symbols. As for date and time format I’ve marked my preferable format with a red underscore, you can edit it to your liking (refer to the manual for PHP date if you’re unsure).
<?php function fetch_tweets($username, $maxtweets) { //Using simplexml to load URL $tweets = simplexml_load_file("http://twitter.com/statuses/user_timeline/" . $username . ".rss"); $tweet_array = array(); //Initialize empty array to store tweets foreach ($tweets->channel->item as $tweet) { //Loop to limitate nr of tweets. if ($maxtweets == 0) { break; } else { $twit = $tweet->description; //Fetch the tweet itself //Remove the preceding 'username: ' $twit = substr(strstr($twit, ': '), 2, strlen($twit)); // Convert URLs into hyperlinks $twit = preg_replace("/(http://)(.*?)/([w./&=?-,:;#_~%+]*)/", "<a href="\0">\0</a>", $twit); // Convert usernames (@) into links $twit = preg_replace("(@([a-zA-Z0-9_]+))", "<a href="http://www.twitter.com/\1">\0</a>", $twit); // Convert hash tags (#) to links $twit = preg_replace('/(^|s)#(w+)/', '1<a href="http://search.twitter.com/search?q=%232">#2</a>', $twit); //Specifically for non-English tweets, converts UTF-8 into ISO-8859-1 $twit = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $twit); //Get the date it was posted $pubdate = strtotime($tweet->pubDate); $propertime = gmdate('F jS Y, H:i', $pubdate); //Customize this to your liking //Store tweet and time into the array $tweet_item = array( 'desc' => $twit, 'date' => $propertime, ); array_push($tweet_array, $tweet_item); $maxtweets--; } } //Return array return $tweet_array; } ?>
Printing out tweets
All you need to do now is to call the above function with your Twitter username and the number of tweets as arguments, and assign it to a value which, after the function has completed, becomes an PHP array containing your tweets. The code for printing the tweets is pretty straightforward. You can customize the wrappings (using lists, span and/or div) so you can style it with CSS in your own way. In the example below I use an unordered list and spans to separate the tweet from the date/time:
<?php // Run the function, with your twitter username and number of tweets as arguments $mytweets = fetch_tweets('yourtwittername', 5); echo '<ul class="twitter-updates">'; foreach ($mytweets as $k => $v) { echo '<li>'; echo '<span class="update">' .$v['desc']. '</span>'; echo '<span class="date">' .$v['date']. '</span>'; echo '</li>'; } echo '</ul>'; ?>
I hope this was useful in some way. Please let me know if this doesn’t work for you, if there is something seriously wrong with it or if you have a better method. I know error handling, such as checking arguments or a timeout if Twitter’s down, should be implemented, but I wanted to keep it as simple as possible.







Morten Rand-Hendriksen
April 12th, 2010 at 20:21
I’ve been looking for a no-JS Twitter feeder for a long time and this one looks like it could be exactly what I need. Thank you very much for posting it. I’ll test it out later today and make some tweaks to the web code so it corresponds with my current style tags and such and post it on my site.
If this works as well as I think it will I’ll write an update to my original and hugely popular Custom Twitter Badge tutorial and link it back to you for much deserved credits.
Tweets that mention Tutorial: Twitter RSS feed parser in pure PHP | Blog -- Topsy.com
April 13th, 2010 at 20:41
[...] This post was mentioned on Twitter by Morten R-H. Morten R-H said: Going to test this out later today: Twitter RSS feed parser in pure PHP http://ow.ly/1xvk0 [...]
JD Hobbs
April 13th, 2010 at 21:54
works perfectly!
will now be replacing your JavaScript twitter feed (Computer Arts tutorial) now!
JD Hobbs
April 18th, 2010 at 17:17
So now got a working version on my website…http://www.jdhobbs.co.uk/
I’ve made some amendments so dates can be displayed as “…ago” instead of just the date, and retweets can now make use of the RT image.
I’ll post some documentation later if anyone wants it.
Ann Christin Kern
April 19th, 2010 at 11:52
I’m glad it was useful
I definitely agree that a time format in “… ago” is more suitable, but I haven’t found a simple, yet correct, way to do this. Tips is greatly appreciated!
Facebook status updates RSS feed parser in pure PHP | Blog
April 19th, 2010 at 15:02
[...] having written a working pure PHP code to fetch and parse both Twitter tweets and general RSS feeds such as WordPress blogs, I was curious of how I could do the same with [...]
Lil
April 23rd, 2010 at 05:08
Love it! Simple, no unnecessary bells and whistles, easy to modify! Thank you!
Fildefer
July 17th, 2010 at 19:31
Nice piece of code.
I turned it into a ModX snippet !!!
It’s my favorite CMS these days.
Thanks !
Stesha
July 21st, 2010 at 16:12
This is great, not overly complicated and gets the job done. Nice work!
Duncan
July 21st, 2010 at 22:14
Great piece of code.
I would rather have the date as “…ago” than the actual date. Any advice on how I can do this?
Thanks.
Ann Christin Kern
July 22nd, 2010 at 08:10
Thanks everyone
Glad it could be of use.
Duncan: There is a great jQuery (Javascript) plugin that converts all your dates and times into “..ago” format: timeago. It will also refresh the time at frequent intervals.
I’ve been using it at work, and it works perfectly. If you open the js-file you can also edit the text that appears (e.g. translate it into another language).
Darfuria
July 27th, 2010 at 18:13
Unfortunately I frequently get the following error when using this script:
failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in /home/notinmyg/public_html/wp-content/themes/nimg/twitter.php on line 6
Andy
August 5th, 2010 at 17:29
Great script!
Idea: anyway to make this retrive the tweets of more than 1 user and display them in Chronological order?
E.g. tweets from your 5 best friends, tweetd from a specific group of people (e.g. your favourite 10 pop stars)
Maybe the list of usernames to get tweets for could be in a comma separated file?
Antone know how to to this?
mark
September 20th, 2010 at 22:46
Very well nice piece of code. The added bit about making all the links, usernames and hash-tags into hyperlink tags was a very nice touch.
DPAM23
November 9th, 2010 at 12:14
I was looking for something like this for a few days, and I finally found it!
great work!
there is also any way to extract by tags?
thanks in advance.
Markus
March 7th, 2011 at 10:09
Awesome snippets, very useful! Thanks a lot!
Drokk
April 15th, 2011 at 13:15
Awesome! Works pefectly. Thank you for saving me a lot of time!
Chris
June 19th, 2011 at 07:41
Your coding is so well written and intuitive to understand. Thanks for saving me a ton of time! beers are on me if you come to Thailand!
Brock Roselle
November 15th, 2011 at 01:16
I love your weblog.. really nice colors & theme. Did you create this web site yourself? Plz reply back as I’m looking to create my own weblog and would like to know wheere u got this from. thanks