Twitter Status With PHP and Twitter JSON (snippet)

Posted on: October 12th, 2012

WARNING: The below code is deprecated as of June 11, 2013. I’ve created a snippet that’s updated here: Twitter Feed With PHP and JSON using API v1.1

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.

$userid = 'johnbhartley'; //your handle
$count = '5';
$responseJson = file_get_contents(''.$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="$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="$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