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.

Share this post:
FacebookTwitterEmailShare