Integrating Twitter feed into your page

Integrating Tweets into your page is not as difficult as one may think. The first step is to find your twitter RSS feed. It would look something like:

https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=Your_User_name

Once you have your RSS Feed URL the following snippet of php will get your tweets:

$doc = new DOMDocument();

if($doc->load('http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=Your_User_name')) {

$max_tweets = 5;    

$i = 1;
foreach ($doc->getElementsByTagName('item') as $node) {
      $tweet = $node->getElementsByTagName('title')->item(0)->nodeValue;

      $tweet = substr($tweet, stripos($tweet, ':') + 1);   
      //Make links into actuall links          
      $tweet = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $tweet);

      //Make replies into links to other twitter users
      $tweet = preg_replace("/@([0-9a-zA-Z]+)/", "<a href=\"http://twitter.com/$1\">@$1</a>", $tweet);

     echo "<li>".$tweet."</li>\n";

   if ($i++ >= $max_tweets)
                       break;
        }
        echo "</ul>\n";
}

Leave a Reply

Your email address will not be published. Required fields are marked *