Grow your CSS skills. Land your dream job.

Last updated on:

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. Permalink to comment#

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

    • 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. can only receive the latter can not appear more

  3. 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. Martin
    Permalink to comment#

    Thanks for this snippets works perfect for me!

  5. 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. Frank
    Permalink to comment#

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

  7. 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. 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);
    
    ?>
    • 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.

    • Thanks for the code, works perfect!

    • 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.

  9. 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. 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. awesome, thank you Chris.

  12. 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. hans chan
    Permalink to comment#

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

  14. 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. 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. Permalink to comment#

    Good tricks!

  17. 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. 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. 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. 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. 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. Permalink to comment#

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

  23. 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. 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. Veronica
    Permalink to comment#

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

  26. 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. usman
    Permalink to comment#

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

  28. Permalink to comment#

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

  29. 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. thanks a lot for simple and great script :)

  31. Andy

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

    Seems promising to me..

  32. 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. 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. c64
    Permalink to comment#

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

  35. 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. 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. 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.

    • 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. 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. 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. XSS WARNING
    Permalink to comment#

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

  41. Edd
    Permalink to comment#

    This script is just what I was looking for!

  42. Abdelali
    Permalink to comment#

    It worked for me, thank’s

  43. 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. Ray
    Permalink to comment#

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

  45. dtgreen

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

  46. Permalink to comment#

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

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

  48. “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. Just thought I’d share I wrote a piece on twitter embedded timelines using API v1.1 OAuth.

    Take it easy guys.

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

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

  52. Suresh
    Permalink to comment#

    How to control the number of tweet

  53. 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. 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

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like ```this```. You don't need to escape code in backticks, Markdown does that for you.

Sadly, it's kind of broken. WordPress only accepts a subset of HTML in comments, which makes sense, because certainly some HTML can't be allowed, like <script> tags. But this stripping happens before the comment is processed by Markdown (via Jetpack). It seems to me that would be reversed, because after Markdown processes code in backticks, it's escaped, thus safe. If you think you can fix this issue, get in touch!

If you need to make sure the code (typically HTML) you post absolutely posts correctly, escape it and put it within <pre><code> tags.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".