Sep 21st

Embedding Your Twitter Feed

An easy way to get your latest tweet onto your website using the php5 function simplexml.

twitter1To go with the redesign of the website I wanted to add the latest tweet from each of the BrightSky team. I didn’t really have the time to look into using the API and looking through various sites i discovered that you can do this.That is my latest tweet in xml format. You can see yours by replacing my user name with your own. Also the count request is the amount of tweets that you;re looking for, I only need one so that’s all I’m requesting. Now to parse it. I used the same php5 extension (simpleXML) that I used to embed the WordPress RSS feeds in my earlier post. What it does is convert the xml sheet into nested objects which you can then easily access. Here’s the function:

function get_status($twitter_id) {
    if(!$xml=simplexml_load_file('http://twitter.com/statuses/user_timeline/' .$twitter_id .'.xml?count=1')){
        trigger_error('Error reading XML file',E_USER_ERROR);
    }
    $status = $xml->status->text;
    $status=preg_replace("/(http:\/\/|www|[a-zA-Z0-9-]+\.|[a-zA-Z0-9\.-]+@)(([a-zA-Z0-9-][a-zA-Z0-9-]+\.)+[a-zA-Z0-9-\.\/\_\?\%\#\&\=\;\~\!\(\)]+)/","<a href=\"http://\\1\\2\">\\1\\2</a>",$status);
    echo '<p>' .preg_replace('/(^|[^\w])@([\d\w\-]+)/', '\\1<a href="http://twitter.com/$2">@$2</a>' ,$status) .'</p>';
    echo '<div>Posted from ' .$xml->status->source .' on '.substr($xml->status->created_at, 0, 10) .'</div>';
}

Its pretty basic. You call it like this:

<?php get_status('yourtwitterusername') ?>

It takes the message and checks it for links which it then wraps in an <a> tag. It also prints the name of the tool that was used to post the message and then the date. Easy cheesy. If you want to print out more than one of your tweets remember to print it out inside a foreach loop.

See it in action.

*ALSO – Does anyone know a decent plugin for WordPress that lets you display code. Its pretty fiddley.

Leave a Reply

Now you've seen what we can do, see what we can do for you