Twitter Status With PHP and Twitter JSON (snippet)

Posted on: October 12th, 2012

Note: the API has a limit of 150 pings per hour, so be careful out there. I’ll have a snippet soon on caching tweets.

<?php        
$userid = 'johnbhartley'; //your handle
$count = '5';
$responseJson = file_get_contents('http://api.twitter.com/1/statuses/user_timeline.json?screen_name='.$userid.'&include_rts=1&count='.$count);

if ($responseJson) {
  $response = json_decode($responseJson);
}   

echo '<ul>';
foreach ($response as $tweet) {
    $tweet_text = $tweet-&gt;text; //get the tweet
    
    // make links link to URL
    $tweet_text = preg_replace("#(^|[n ])([w]+?://[w#$%&~/.-;:=,?@[]+]*)#is", "\1&lt;a href='\2'&gt;\2&lt;/a&gt;", $tweet_text); 
    
    // make hashtags link to a search for that hashtag
    $tweet_text = preg_replace("/#([a-z_0-9]+)/i", "&lt;a href="http://twitter.com/search/$1"&gt;$0&lt;/a&gt;", $tweet_text);
    
    // make mention link to actual twitter page of that person
    $tweet_text = preg_replace("/@([a-z_0-9]+)/i", "&lt;a href="http://twitter.com/$1"&gt;$0&lt;/a&gt;", $tweet_text);
    
    // display each tweet in a list item
    echo "&lt;li&gt;" . $tweet_text . "&lt;/li&gt;n";
} 
echo '</ul>';
?>

This snippet will help you add your twitter status to any site with PHP and the Twitter JSON file. It is output into a list and the number of tweets is controlled by the variable $count. Be sure to switch out my name for your twitter handle, unless you want to show all of my tweets, which would be weird.

This is just a quick fix to what I had previously used, which was the XML file, which as of yesterday, no longer seemed to work. Happy status-showing and as always, let me know if you’ve found a better way to pull this off.

Note: More explanation to come laters.

Tags: , , , , , ,

previous post: Custom Taxonomy Category Dropdown next post: Getting Started With Sublime Text 2 Package Control

  • Masterpage

    And I was wondering what had happened with fetching twitter statuses to my website! Thanks for this post, it’s solved my task.

    Twitter has become a little bit annoying with their policy changes (as of August 2012) and this quiet deprecation of XML format…

    • johnbhartley

      Yeah, using the API is a bit more difficult and actually, unless you’re embedding tweets with the exact “Twitter” look, they kind of frown on it. Getting to a point where I may not show my tweets on my website anymore. Reference: https://dev.twitter.com/terms/display-requirements

  • http://www.facebook.com/sacha.veyrier Sacha ‘Vaati’ Veyrier

    ONLY WORKING TWITTER SNIPPET ON THE INTERNET :D
    Thanks a lot, I went through a lot of snippets , none were working ; but this one works just fine. Thanks again :)

    • johnbhartley

      Glad you liked it. I got tired of seeing the XML snippets so I figured out the API one day. Once I had it I knew it needed to be shared. Spread the word!