Get Your Most Recent Twitter Status Using PHP

I wanted a very simple PHP function to return my current Twitter status so I could put it on my website. Alas, every solution I found online required an XML parser. Of course, they all returned a lot more than the most recent status, but I didn’t want any of that.

Since my updates are not protected (i.e. they appear in the public timeline), I knew I could use Twitter’s API to obtain my status without authenticating. The URL to access this information is http://twitter.com/statuses/user_timeline/id.format, where id is your numerical Twitter ID and format is one of xml, rss, json, or any other format supported by the API.

To find your numerical Twitter ID, login to Twitter and click on your RSS feed (bottom of the page). The URL will look something like http://twitter.com/statuses/friends_timeline/12345678.rss. Your ID will be the 12345678.

The following PHP function accesses the specified timeline and returns only the most recent (current) update.

<?php
function twitter_status($twitter_id, $hyperlinks = true) {
    $c = curl_init();
    curl_setopt($c, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/$twitter_id.xml?count=1");
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    $src = curl_exec($c);
    curl_close($c);
    preg_match('/<text>(.*)<\/text>/', $src, $m);
    $status = htmlentities($m[1]);
    if( $hyperlinks ) $status = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"\\0\">\\0</a>", $status);
    return($status);
}
?>

Note the $hyperlinks parameter, which will enable/disable anchor tags from appearing in your statuses when they contain a URL.

Also note that this function requires the PHP cURL library, which is enabled by default on most shared web hosts.

Sometimes Twitter can be a little slow, and using this function on your webpage when Twitter is lagging will cause your page to lag. I found it best to call this function via AJAX after your page loads to prevent such lag times.

Special thanks to Jamie Bicknell for his tip to speed up the load time.

If you enjoyed this article, please share it with a friend!

23 Responses to Get Your Most Recent Twitter Status Using PHP

  1. Harsh says:

    Thanks for the script Cory. I wonder if we can also display the time next to the status?

    Even better would be to display the time as a countup clock. (like: http://www.devhunters.com/javascript-programming/4403-count-up-counter-javascript.html)

    Any idea?

  2. Craig Keller says:

    I dont get it. It doesnt work on my site. I have mediatemple which has curl. How does this get my twitter id? it probably doesnt, so where to i plug that into your code?

  3. Cory LaViska says:

    @Craig: try this sample code:

    [function code here]

    echo twitter_status(123456);

    …where ’123456′ is your Twitter ID.

  4. Cory. Great script (and how-to article).
    Here’s my adaptation as an object (with caching). You can see it working at http://bulletsburning.com

    < ?php

    class twitter{
    const CACHE_FNAME = 'sessions/twitter.status';

    function __construct($id,$addAnchors=true){
    $this->id = $id;
    $this->addAnchors = $addAnchors;
    $this->status = $this->load();
    }

    private function load(){
    $ret = ”;

    $life = (time() – filectime(self::CACHE_FNAME));
    if($life < (15*60) and $life > 0)
    $ret = trim(file_get_contents(self::CACHE_FNAME));

    return $ret;
    }

    private function save(){
    file_put_contents(self::CACHE_FNAME,$this->status);
    }

    function getStatus(){
    // fetch new status
    if(!strlen($this->status)){
    $this->status = $this->fetch();
    $this->save();
    }

    return $this->status;
    }

    private function fetch(){
    // init
    $c = curl_init();
    curl_setopt($c,CURLOPT_URL,
    “http://twitter.com/statuses/user_timeline/$this->id.xml”);
    curl_setopt($c,CURLOPT_RETURNTRANSFER,1);

    // exec
    $src = curl_exec($c);
    curl_close($c);
    preg_match(‘/(.*)< \/text>/’,$src,$m);
    $status = htmlentities($m[1]);

    // add anchors?
    if($this->addAnchors)
    $status = ereg_replace(
    “[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]”,
    \\0“,
    $status);

    return($status);
    }
    }

    ?>

    to invoke, one would:

    < ?php

    $t = new twitter('myidXXXX');
    $status = $t->getStatus();
    echo “My twitter status is ‘$status’\n”;

    ?>

  5. Ben says:

    Thought I should post this in case anyone is interested… Tweaked Nathanael’s code to include the time the twitter was posted:

    < ?php

    class twitter{
    const CACHE_FNAME = 'resources/twitter.status';

    function __construct($id,$addAnchors=true) {
    $this->id = $id;
    $this->addAnchors = $addAnchors;
    $this->status = $this->load();
    }

    private function load() {
    $ret = ”;

    $life = (time() – filectime(self::CACHE_FNAME));
    if($life < (10*60) and $life > 0)
    $ret = trim(file_get_contents(self::CACHE_FNAME));

    return $ret;
    }

    private function save() {
    file_put_contents(self::CACHE_FNAME,$this->status);
    }

    function getStatus() {
    // fetch new status
    if(!strlen($this->status)){
    $this->status = $this->fetch();
    $this->save();
    }

    return $this->status;
    }

    // http://twitter.pbwiki.com/RelativeTimeScripts
    function get_elapsedtime($time) {
    $gap = time() – $time;
    if ($gap < 5) {
    return 'less than 5 seconds ago';
    } else if ($gap < 10) {
    return 'less than 10 seconds ago';
    } else if ($gap < 20) {
    return 'less than 20 seconds ago';
    } else if ($gap < 40) {
    return 'half a minute ago';
    } else if ($gap < 60) {
    return 'less than a minute ago';
    }
    $gap = round($gap / 60);
    if ($gap < 60) {
    return $gap.' minute'.($gap > 1 ? ‘s’ : ”).’ ago’;
    }
    $gap = round($gap / 60);
    if ($gap < 24) {
    return 'about '.$gap.' hour'.($gap > 1 ? ‘s’ : ”).’ ago’;
    }
    return date(‘h:i A F d, Y’, $time);
    }

    private function fetch() {
    // init
    $c = curl_init();
    curl_setopt($c,CURLOPT_URL,”http://twitter.com/statuses/user_timeline/$this->id.xml”);
    curl_setopt($c,CURLOPT_RETURNTRANSFER,1);

    // exec
    $src = curl_exec($c);
    curl_close($c);
    preg_match(‘/(.*)< \/text>/’,$src,$m);
    $status = htmlentities($m[1]);

    // add anchors?
    if($this->addAnchors)
    $status = ereg_replace(
    “[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]”,
    \\0“,
    $status);

    // get time
    preg_match(‘/(.*)< \/created_at>/’,$src,$m);
    $created_at = $this->get_elapsedtime(strtotime($m[1]));

    return $status . “
    ” . $created_at;
    }
    } ?>

    Like Nathanael’s example, to invoke, one would:

    < ?php

    $t = new twitter('mytwitterid');
    $status = $t->getStatus();
    echo “My twitter status is ” . $status;

    ?>

  6. Ben says:

    Minor edit to above post…

    Twitter does have a 100 request limit per hour. Just in case you get a lot of traffic and you hit that limit for some reason, add these lines to show an error message:

    // check for errors
    if(!$status) { return “Error connecting to Twitter!”; }

    just below this statement in fetch():

    $status = htmlentities($m[1]);

    and then modify the statement above to add an “@” to hide the server error (if there is one):

    $status = @htmlentities($m[1]);

  7. lex says:

    Hi
    How to grab the first 5 headlines of google news using this method? Or any website that allows querying

  8. Hello,

    By adding “?count=1″ to the end of the twitter URL it reduces the size of the response and therefore making it much faster. Not fast enough to not use AJAX, but still much MUCH faster.

    http://twitter.com/statuses/user_timeline/$twitter_id.xml?count=1

  9. Cory LaViska says:

    @Jamie: you’re absolutely right. The load time is significantly faster :) Great tip!

  10. I’ve found a faster method, and is only 5 lines:

    < ?php
    $id = 'jamiebicknell';
    $tweet = new SimpleXMLElement('http://twitter.com/users/show/'.urlencode($id).'.xml',NULL,TRUE);
    echo $tweet->status->text.’ – ‘.date(“j M y g:i a”,strtotime($tweet->status->created_at));
    ?>

    I’m a bit of a perfectionist when it comes to efficiency and coding

  11. Giorgos says:

    thankx,especially Jamie Bicknell

  12. James Stone says:

    Hi Jamie,

    Hwo would you loop through that to get the latest X examples… seems really simple… well done

  13. John says:

    I’m particularly fond of:

    < ?php
    function twitterStatus($twitterID, $hyperlinks = true)
    {
    $tweet = new SimpleXMLElement('http://twitter.com/statuses/user_timeline/' . $twitterID . '.xml?count=1', null, true);
    $status = @$tweet->status->text;

    if (!$status)
    {
    return ‘Not Available’;
    }

    if ($hyperlinks)
    {
    $status = ereg_replace(“[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]”, “\\0“, $status);
    }

    return $status;
    }
    ?>

  14. @James Stone – I would only use the code I stated on the 28th Jan to display a single status. For multiple statuses see code below.

    @John – Possibly two things I don’t like about that code. First, the @ suppresses errors and makes the code around 10x slower even if it is a success. Secondly, that ereg_replace function is a bit slow. I always prefer preg_replace over ereg, but that’s just me. You can adjust that for preg_replace no worries. Also, dont forget that when someone tweets a reply, the @jamiebicknell also needs to be a link, see my code below for the preg_replace.

    $id = “jamiebicknell”;
    $tweet = new SimpleXMLElement(‘http://twitter.com/statuses/user_timeline/’.urlencode($id).’.xml?count=5′,NULL,TRUE);
    foreach($tweet->status as $t) {
    echo preg_replace(“/@([A-Za-z0-9_]+) /”,”$0“,$t->text) . ‘

    ‘;
    }

  15. Cory LaViska says:

    @Jamie: There’s only one thing I noticed about this…sometimes it hangs (when Twitter lags?) and thus the remainder of the page fails to load if you call it inline. I actually had to remove the status from ABS because of this.

  16. @Cory: This can happen, I generally use this snippet in an AJAX environment so it will load after the main content of the website loads, therefore not affecting the overall loadtime of the website. You can add in the status check in JS so that if the twitter does lag out, then just stop and try again in 30 seconds or something.

  17. Hi, I’m in need of a bit of help…

    I have got the twitter code working on my site and you can see it live at http://www.jdfulton.com.au

    The code im using is:

    < ?php
    function twitter_status($twitter_id, $hyperlinks = true) {
    $c = curl_init();
    curl_setopt($c, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/$twitter_id.xml?count=1");
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    $src = curl_exec($c);
    curl_close($c);
    preg_match('/(.*)< \/text>/’, $src, $m);
    $status = htmlentities($m[1]);
    if( $hyperlinks ) $status = ereg_replace(“[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]”, “\\0“, $status);
    return($status);
    }
    echo twitter_status(22884262);
    ?>

    The problem is I want the time the twit was published to be posted as well. I have tried the other codes which are supposed to do that without luck. They have all returned errors.

    Any help would be much appreciated, as I said im not to good with PHP

    Thanks

  18. Neat, but why not just google “php twitter class” and grab one of the many php classes designed to talk to twitter via API calls? Call it once every 10 minutes and cache the results so you don’t overuse your API call count?

  19. Rahul says:

    echo preg_replace(“/@([A-Za-z0-9_]+) /”,”$0“,$t->text) . ‘

    ‘;

    this doesnot work

  20. Rahul says:

    sorry ur code works with xml but not with json… wonder why

  21. Jeff says:

    James D Fulton, in order to display the time you will have to do antother preg_match like this:
    preg_match(‘/(.*)< \/created_at>/’, $src, $m);
    $time = htmlentities($m[1]);

    of course then you can take that time and manipulate it with PHP.

  22. Oto Brglez says:

    This is snippet based on original code above, but it uses JSON and it has counter if you wish to get more than one twit.

    < ?php

    function get_twits($id, $count=5, $links=true){
    $c = curl_init();
    curl_setopt($c, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/".$id.".json?count=".$count);
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    $out = json_decode(curl_exec($c));
    curl_close($c);

    if($links) for($i=0; $i<$count; $i++)
    $out[$i]->text = ereg_replace(“[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]”,
    \\0“, $out[$i]->text);
    return $out;
    }

    $data = get_twits(“otobrglez”,5);
    foreach($data as $twit){
    echo $twit->text. “\n”;
    };

    ?>

  23. Joel Wallis says:

    The Elliot Haughin, a CodeIgniter developer have created a library to use the Twitter API.
    It’s a simple class that makes this work easy.

    The link:
    http://www.haughin.com/code/twitter/