Twitter Status Updates On Your Website Using PHP

Twitter Status Updates On Your Website Using PHP Posted May 23, 2009 @ 5:43pm by Phil

I started using Twitter a while back, but lost interest after about a month. Most of the people I was following were using their accounts as an RSS feed or posting irrelevant updates. However, the recent explosion of people's interest (no doubt due to its appearance on Oprah) has caused me to rethink my position. I decided that using Twitter I could post updates and ideas not worthy of an entire post. So being a programmer I went ahead and wrote this little PHP function to retrieve my status updates for displaying on this website:

<?php
  function twitter_updates ($username, $password)
  {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, "http://twitter.com/statuses/user_timeline.xml");
    curl_setopt($curl, CURLOPT_GET, true);
    curl_setopt($curl, CURLOPT_USERPWD, $username.":".$password);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $xml = curl_exec($curl);
    curl_close($curl);
    
    $matches = array();
    preg_match_all("/\<created_at\>([^\<\>]*)\<\/created_at\>[^\<\>]*\<id\>[^\<\>]*\<\/id\>[^\<\>]*\<text\>([^\<\>]*)\<\/text\>/", $xml, $matches, PREG_SET_ORDER);
    
    $status = array();
    foreach ($matches as $match)
    {
      $status[] = array("created_at" => strtotime($match[1]), "text" => $match[2]);
    }
    
    return $status;
  }
?>

Download Source: twitter_updates.php

Note: Twitter has a limit of 60 requests per minute so on most sites (not mine) this function won't due. I will be releasing another article soon with improved code with caching.

Update: An example on how to cache the result for better performance can be found in this article.

Tags: PHP/MySQL, Twitter, Webmasters Tips