Twitter Status on Your Blog or Website

Everyone wants to show twitter status on their website or blog. This is how that it can be done using PHP. If you are using a Blogging platform such as WordPress you can use a plug-in that supports embedding PHP code into your blog. There are many providers if you search the listings.

You can embed the following code directly into WordPress custom text area with PHP support. There are many twitter widgets available, but most support only a single user. With this you can show the status from multiple accounts. If you increase the count at the end of the URL you will need to check for multiple values inside the function. ($twitter_url)

Here Goes the Code:


<?php
function get_plain_status($username)
{
  $twitter_url = "http://twitter.com/statuses/user_timeline/$username.xml?count=1";  
  try {
    $buffer = @file_get_contents($twitter_url);
    $xml = new SimpleXMLElement($buffer);
    $status_item = $xml -> status;
    $status = $status_item -> text; 
    return "<li><a href=\"http://twitter.com/$username\">@$username</a>: $status</li>";
  } catch (Exception $e) {
    return "<li><a href=\"http://twitter.com/$username\">@$username</a></li>";
  }
} 
echo '<ul>';
echo get_plain_status('user_1');
echo get_plain_status('user_2');
echo get_plain_status('user_3');
echo get_plain_status('user_4');
echo '</ul>';
?>

The twitter URL call sometimes fails due to the load at their servers. So the try-catch is used to show a default text at that time. You can put anything you want.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s