Mar 12, 2010 2
A better way to grab your tweets
Most of my clients are on twitter, this results in my clients wanting to show their latest tweets on their home page.
While Twitter provide JavaScript ‘badges’ to show your latest tweets, it it sluggish and what happens if a user has JavaScript disabled?
My workaround for this was using php to parse the users RSS feed.
//RSS Feed URL
$rss_url = “http://twitter.com/statuses/user_timeline/14942878.rss”;
if (!$rss_data = @file_get_contents($rss_url)) {
echo "Oh snap, it seems twitter is down :(";
} else {
$rss_xml = SimpleXML_Load_String($rss_data);
$channel_title = $rss_xml->channel->title;
$channel_link = $rss_xml->channel->link;
$tweets = array();
foreach ($rss_xml->channel->item as $item) {
$item_title = $item->title;
$item_link = $item->link;
$item_description = $item->description;
$tweet = explode(": ", $item_title);
$tweetmessage = preg_replace("/(http:\/\/[^\s]+)/", "$1", $tweet[1]);
$tweetmessage = preg_replace("/(@[^\s]+)/", "$1", $tweetmessage);
$tweets[] = $tweetmessage ;
}
echo $tweets[0] ;
}
This chuck of code uses a regular expression to parse the XML of your RSS feed, puts each tweet into an array.
Example: Display your 5 most recent tweets:
echo $tweets[0] ;
echo $tweets[1] ;
echo $tweets[2] ;
echo $tweets[3] ;
echo $tweets[4] ;
Enjoy!

Discussions