thoughts & working experiments connected to our work

Trouble with your twitter feed?

Quick OAuth and Twitter API v1.1 example.

Twitter api v1.0 is now offically switched off as of June 11th. For many app builders who havent kept abrest there could be some real pain involved in switching to the newer REST API v1.1. If you are using a CMS like Joomla , Drupal, WordPress etc and using twitter feeds to pull your tweets into a block or module then you might also need to revise your code. What follows is a Quick OAuth and Twitter API v1.1 example.


References:

This is made possible by James Mallinson's php wrapper availbale on github here: https://github.com/J7mbo 

You might also want to check out this reference here: http://stackoverflow.com/questions/12916539/simplest-php-example-retrieving-user-timeline-with-twitter-api-version-1-1/15314662#15314662 

So.... lets get started...

First include wrapper and set your tokens

require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
    'oauth_access_token' => "XXXXXXXXXX",
    'oauth_access_token_secret' => "XXXXXXXXXX",
    'consumer_key' => "XXXXXXXXXXXX",
    'consumer_secret' => "XXXXXXXXXXXX"
);

Then set your api call

$url = 'https://api.twitter.com/1.1/blocks/create.json';
$requestMethod = 'POST';

Then do the request

/** Perform a GET request and echo the response **/
/** Note: Set the GET field BEFORE calling buildOauth(); **/

$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$getfield = '?screen_name=[yourscreen name]&count=6';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$tweets = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$data = json_decode($tweets,true);

Then play with the data ;)

Some regular expressions are used to turn links into links and hashes into stream search links.

foreach ($data as $tweet):
    $text = $tweet["text"];
    $text = preg_replace('@(https?://([-\w\.]+)+(/([\w/_\.]*(\?\S+)?(#\S+)?)?)?)@', '$1', $text);
    $text = preg_replace('/@(\w+)/', '@$1', $text);
    $text = preg_replace('/\s#(\w+)/', ' #$1', $text);
    $unix_time = strtotime($tweet["created_at"]);
    $pretty_time = timeAgo($unix_time);
endforeach

A helper function for formatting the twitter time

The timeago function

$pretty_time = timeAgo($unix_time);

helps to format the wtitter time in to the most recent 'time ago' tweet.

function  timeAgo($timestamp, $granularity=1, $format='Y-m-d H:i:s'){
        $difference = time()-(60*60) - $timestamp;
       // $difference = $difference+21600; // compensate for US time difference
        if($difference < 0) return '0 seconds ago';
//        elseif($difference < 864000){
                $periods = array('week' => 604800,'day' => 86400,'hr' => 3600,'min' => 60,'sec' => 1);
                $output = '';
                foreach($periods as $key => $value){
                        if($difference >= $value){
                                $time = round($difference / $value);
                                $difference %= $value;
                                $output .= ($output ? ' ' : '').$time.' ';
                                $output .= (($time > 1 && $key == 'day') ? $key.'s' : $key);
                                $granularity--;
                        }
                        if($granularity == 0) break;
                }
                return ($output ? $output : '0 seconds').' ago';
 //       }   else return date($format, $timestamp);
}

That's about it. However we want to remember that Twitter rate limits your api calls so in an ideal world we will cache the json output to a file and set a time limit for calling the twitter API again to avoid hitting the rate limit. The limit on calls is roughly 180 per 15 mins. On a busy site that is going to max out pretty quick.

We will turn this into an installable Joomla 2.5 3.0 extension soon

Recent clients