Get Latest Twitter Status

The code below no longer works as-is with the Twitter API update to 1.1 as of 2013-06-11. The 1.1 API requires oAuth which requires a server side component. Here's a PHP way to interact with the new API. Googling around will find you many other libraries and such. There is an all-JavaScript method for getting tweets, but it may be a bit of a loophole that you may not want to count on.
<?php

function getTwitterStatus($userid){
$url = "https://api.twitter.com/1/statuses/user_timeline/$userid.xml?count=1&include_rts=1callback=?";

$xml = simplexml_load_file($url) or die("could not connect");

       foreach($xml->status as $status){
       $text = $status->text;
       }
       echo $text;
 }

// USAGE
getTwitterStatus("chriscoyier");

?>

Comments

  1. User Avatar
    Dyllon
    Permalink to comment#

    All I get is a ‘Could not Connect’ Error. Code doesn’t seem work.

    • User Avatar
      Will
      Permalink to comment#

      The code works. There are a couple reasons you might get a “Could no Connect” that come to mind:

      1. Your installation of PHP does not support simple_xml
      2. Your server is not able to connect to an external site.

      The first scenario is probably more likely.

  2. User Avatar
    Jorge Martinez
    Permalink to comment#

    can only receive the latter can not appear more

  3. User Avatar
    Henrique Mattos
    Permalink to comment#

    Another reason for the code to not work properly is that the twitter account used to retrieve the status update may be ‘locked’ (private accounts).

    You should set it up to public status update ;)

  4. User Avatar
    Martin
    Permalink to comment#

    Thanks for this snippets works perfect for me!

  5. User Avatar
    Greg
    Permalink to comment#

    I would advise against using the XML format, at least for now. It appears that retweets are not included in the XML and JSON feeds. That wouldn’t be so bad, except that it doesn’t just skip a retweet – it returns a blank tweet!

    To get around this I use the RSS format. That comes with its own unique challenges and a different XML structure but at least it returns those retweets.

    More info:

    http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-user_timeline

  6. User Avatar
    Frank
    Permalink to comment#

    How would you change it to show the last X tweets instead of just 1?

    • User Avatar
      Kartik Iyer
      Permalink to comment#

      in $url instead of 1 in count use ‘x’ where ‘x’ defines the number of tweets.

  7. User Avatar
    Kim
    Permalink to comment#

    I implemented the above code but the links in my tweets are not active even though they are active on my twitter page. Have any thoughts?

  8. User Avatar
    Walter
    <?php
    
    function getLastXTwitterStatus($userid,$x){
    $url = "http://twitter.com/statuses/user_timeline/$userid.xml?count=$x";
    
    $xml = simplexml_load_file($url) or die('could not connect');
    	echo '<ul>';
           foreach($xml->status as $status){
           $text = twitterify( $status->text );
    	   echo '<li>'.utf8_decode($text).'</li>';
           }
        echo '</ul>';
     }
    
     function twitterify($ret) {
      $ret = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1<a href=\"\\2\" >\\2</a>", $ret);
      $ret = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1<a href=\"http://\\2\" >\\2</a>", $ret);
      $ret = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" >@\\1</a>", $ret);
      $ret = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?q=\\1\" >#\\1</a>", $ret);
    return $ret;
    }
    
    //my user id kenrick1991
    getLastXTwitterStatus('kenrick1991',5);
    
    ?>
    • User Avatar
      Chris Coyier

      I know you nearly lost your shit trying to publish this code, but it says everything you need to know in the remember section right by this comment form.

    • User Avatar
      Frederick
      Permalink to comment#

      Thanks for the code, works perfect!

    • User Avatar
      Asmi Rana
      Permalink to comment#

      i used code it works for me but i cannot get the date of tweets. Can you help me to get the tweet date.

    • User Avatar
      Iran
      Permalink to comment#

      Don’t work this code :( ..

  9. User Avatar
    Nic Boileau
    Permalink to comment#

    Not sure if this has been posted, I found a slight error with your foreach loop.

    if you set the ?count=5 (or something other than one) you will only echo the 5th most recent tweet you’ve made. If that is what you’re after, great, but if you want to show the 5 most recent tweets, you’ll need to put the “echo $text;” within the foreach:

    <?php 
    
    foreach ($xml->status as $status) {
      $text = $status->text;
      echo $text."<br />";
    }      
    
    //my user id kenrick1991
    getTwitterStatus("kenrick1991");
    
    ?>

    in the $url, change ?count=1 to ?count=5 or something other than one

  10. User Avatar
    Justin
    Permalink to comment#

    Well, it worked perfectly at first, then after refreshing the page, it gave a could not connect to server error. Wonder why it worked initially?

  11. User Avatar
    Irfan Suleman
    Permalink to comment#

    awesome, thank you Chris.

  12. User Avatar
    DocHollywood
    Permalink to comment#

    Both versions works great for me, now to just stylize it and put it on my homepage for my users. Thanks!

  13. User Avatar
    hans chan
    Permalink to comment#

    i got it every thing just working fine :) thx Chris

  14. User Avatar
    Michael Shur
    Permalink to comment#

    It works intermittently for me. It will be displaying everything fine and then, a moment later, it stops and I get the “Could not Connect” error.

    Any ideas?

  15. User Avatar
    Alex Glover
    Permalink to comment#

    I was having issues getting it to work and I realized that

    $text = $status->text;

    would need to be

    $text .= $status->text;

    Otherwise the code will only print one.

  16. User Avatar
    Lafaz
    Permalink to comment#

    Good tricks!

  17. User Avatar
    Nicholas Camp
    Permalink to comment#

    I made some modifications to the script. Hope this help someone! :) `

    < ?php
      function getTwitterStatus($userid){
        $i = 1;
        do {
          $url = "http://twitter.com/statuses/user_timeline/$userid.xml?count=$i";
          $i++;
          $xml = simplexml_load_file($url) or die("could not connect");
          $text = utf8_decode($xml->status->text);
        } while (empty($text));
        $text = ereg_replace("[[:alpha:]]+://[^[:space:]]+[[:alnum:]/]", "\", $text);
        echo $text;
      }
      getTwitterStatus("nicholascamp");
    ?>
  18. User Avatar
    Asmi Rana
    Permalink to comment#

    i used @Walter code it works for me but i cannot get the date of tweets. Can anyone help me to get the tweet date.

  19. User Avatar
    commonmind

    I’m working with a Drupal install, trying to forego using OAuth and the current iteration of the Twitter module, using this code instead. Unfortunately the “Could not connect” error is site crippling for me. It gives me a white screen and completely locks me out of accessing my site, until the error finally just (randomly) ceases and the code is functional again. Is there any way to stop this behavior, or a bit of code that might work “better” for my needs? Any help is appreciated. Thanks!

  20. User Avatar
    Sotiris Kalathas

    I changed a little something in Walter’s code because Greek characters showed up like questionmarks for me.

    So I replaced utf8_decode($text) with html_entity_decode($text) and now my Greek chars are just fine!


    <?php

    function getLastXTwitterStatus($userid,$x){
    $url = "http://twitter.com/statuses/user_timeline/$userid.xml?count=$x";

    $xml = simplexml_load_file($url) or die('could not connect');
    echo '<ul>';
    foreach($xml->status as $status){
    $text = twitterify( $status->text );
    echo '<li>'.utf8_decode($text).'</li>';
    }
    echo '</ul>';
    }

    function twitterify($ret) {
    $ret = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1<a href=\"\\2\" >\\2</a>", $ret);
    $ret = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1<a href=\"http://\\2\" >\\2</a>", $ret);
    $ret = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" >@\\1</a>", $ret);
    $ret = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?q=\\1\" >#\\1</a>", $ret);
    return $ret;
    }

    //my user id kenrick1991
    getLastXTwitterStatus('kenrick1991',5);

    ?>

  21. User Avatar
    John
    Permalink to comment#

    I have been checking out different way’s to embed twitter in php and this is by far the best and easiest I’ve seen.

    Is there a way to embed hashtag’s like through twitter search instead of a user id? Would be great for events!

  22. User Avatar
    Jom Gapuz
    Permalink to comment#

    How do I cache my tweet because my page seem to load slower than normal?

  23. User Avatar
    Tezza
    Permalink to comment#

    Does anybody know how I can use PHP to grab the StatusesCount from a Twitter account and then return to it to a webpage as a plain text number to format with CSS? I am currently displaying the 5 most recent tweets and below have a link ‘view more tweets’ that links to the twitter account but I am keen to say ‘view more tweets, we have x available to read’. Where x is the count that gets returned through the PHP. Can anybody help, I thought it would be easy to find, but having searched for the past two hours I haven’t been able to track down how to do it. Thanks T

  24. User Avatar
    John Hartley
    Permalink to comment#

    Great thread! I went with the @walter code for a recent theme build and to switch out the $userid with a name input by the theme user I just added a variable at the top and replaced the username in the function call at the bottom:

    
    <?php
    
    	$userid = $some_global_class->get_your_thingname();
    
    	function getLastXTwitterStatus($userid,$x){
    
     //then the middle stuff
    
            getLastXTwitterStatus($userid,5);
    
    php ?>
    
    
    

    Nice for a WordPress theme build.

  25. User Avatar
    Veronica
    Permalink to comment#

    Is there a way to use Walter’s code but exclude any @replies?

  26. User Avatar
    DLS
    Permalink to comment#

    Is there ANY way to display multiple tweets, but only one at a time? Or even put them all in a singular line with something like a bunch of hyphens separating them? I’m trying to create a scrolling ticker..

  27. User Avatar
    usman
    Permalink to comment#

    Just Click on this Link
    https://twitter.com/statuses/user_timeline/ranasaani.json
    You will get the Json object

  28. User Avatar
    VIjay
    Permalink to comment#

    @usman this is the simplest way I have seen thanks..

  29. User Avatar
    Prasad

    I am retrieving latest tweet with count=1.
    But when i delete the latest tweet, twitter returns blank. I am using XML/JSON format.

  30. User Avatar
    Aaryadev

    thanks a lot for simple and great script :)

  31. User Avatar
    Andy

    I found a class here on this site http://www.thetutlage.com/post=TUT177

    Seems promising to me..

  32. User Avatar
    Jason
    Permalink to comment#

    How do you make any links in the tweet hyperlinked?

    I got it to work, but the link is text not a link.

    thanks

  33. User Avatar
    Ankur Gupta
    Permalink to comment#

    It was working until yesterday, but today when i checked, its giving could not connect message for my website http://ankurgupta.com/ and coz of this error the full page is also not loading :(

  34. User Avatar
    c64
    Permalink to comment#

    awesome! worked for me.. thx a lot… God bless you.

  35. User Avatar
    classified ads
    Permalink to comment#

    Hi! I could have sworn I’ve been to this site before but after checking through some of the post I realized it’s new
    to me. Anyhow, I’m definitely delighted I found it and I’ll be book-marking and checking back often!

  36. User Avatar
    Serge
    Permalink to comment#

    It absolutely works, but a “linkify” option for the status would’ve suited more people I suppose.

    Anyways, like one of the Johns above said, this is the easiest solution that I know of. Thanks!

    Michael Shur, that intermittently “could not connect” issue is a Twitter one rather than a script problem. The worst case scenario where you don’t blame Twitter or the script is a setting on your server, but I doubt it.

  37. User Avatar
    Sarat
    Permalink to comment#

    Thanks a lot for the function. How can I overcome the “Rate limit exceeded. Clients may not make more than 150 requests per hour.” I see that using OAuth is one of the solutions, but not sure exactly how to implement it. Any help would be great.

    Thanks.

    • User Avatar
      AJ
      Permalink to comment#

      What I did was cache the last tweet in a file, that way if you hit the rate limit error or for any reason cannot get the latest tweet from twitter, it will use the local cache. This prevents errors on your site. You can find it here

  38. User Avatar
    Sitebee
    Permalink to comment#

    Works for me and simple to use too, Ive tried about 3 different widgets in the last hour that did not meet my requirements. Was starting to drive me mad… Thanks :)

  39. User Avatar
    Dave
    Permalink to comment#

    Great code works perfectly for me!

    Well.. except for one thing

    Is there any way to just display normal tweets rather than direct messages/mentions/replies?

  40. User Avatar
    XSS WARNING
    Permalink to comment#

    FIX:
    $userid = htmlspecialchars($userid);
    $url = ‘url?’ . $userid . ‘url’;

  41. User Avatar
    Edd
    Permalink to comment#

    This script is just what I was looking for!

  42. User Avatar
    Abdelali
    Permalink to comment#

    It worked for me, thank’s

  43. User Avatar
    Maxim
    Permalink to comment#

    I am working on a website for a client and he wants his entire tweet to link to the individual tweet on twitter. I’ve wrapped the ul in an a tag, which works fine, but I am not sure what php I need to put in the href attribute to make it link to the individual tweet.

    Could any of you help me out?
    Thanks in advance!

  44. User Avatar
    Ray
    Permalink to comment#

    Just wanted to say thanks for the code! Works perfectly.

  45. User Avatar
    dtgreen

    Perfect! Quick, simple and does the job. CSS Tricks strikes again!

  46. User Avatar
    Rui
    Permalink to comment#

    Hi! Stopped working yesterday!! Any changes in the twitter API? Thanks.

  47. User Avatar
    Marcio Toledo
    Permalink to comment#

    Twitter discontinued with XML, need fix to work with JSON and API 1.1

  48. User Avatar
    Dan Wiseman
    Permalink to comment#

    “Twitter discontinued with XML, need fix to work with JSON and API 1.”

    Yes, a fix or substitute would be extremely useful please. Anyone?

    It would be great for someone to explain a way to get Twitter posts in plain text format rather than having to use the Twitter widget.

  49. User Avatar
    shoogle designs
    Permalink to comment#

    Just thought I’d share I wrote a piece on twitter embedded timelines using API v1.1 OAuth.

    Take it easy guys.

  50. User Avatar
    Summit Web Solutions
    Permalink to comment#

    Thanks to the above 2 posts for their updates, both are appreciated!

  51. User Avatar
    web tasarım
    Permalink to comment#

    After twitter api 1.1 no allowed for basic auth
    Try to check https://dev.twitter.com/docs/api/1.1

  52. User Avatar
    Suresh
    Permalink to comment#

    How to control the number of tweet

  53. User Avatar
    http://rachelshannon.weebly.com
    Permalink to comment#

    For this you need to work closely with roofing Melbourne experts to ensure
    that you have also considered the weight and working load your roof will be able to bear.

    (3) It is also useful if you have pets, would keep
    lights around the barn unwelcome visitors. To add insult to injury, the roofing contractor
    that would put his workers up on your roof without insurance is the same contractor that would probably ignore most safety requirements.

  54. User Avatar
    sandeep jain
    Permalink to comment#

    <?php $ret = preg_replace("/#(\w+)/", "#\\1“, $ret); ?>
    <?php $ret = preg_replace("/#(\w+)/", "#\\1“, $ret); ?>
    Thanks Walter
    in place of first line use second line

    above two comments are due to without php

  55. User Avatar
    Leandro
    Permalink to comment#

    everything change: https://dev.twitter.com/rest/reference/get/statuses/user_timeline

    new twitter docs to api get->status->usertimeline

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag