Twitter Feed With PHP and JSON using API v1.1

I put off updating my Twitter snippet until Twitter finally pulled the plug on API v1.0, so here is a snippet to pull in your Twitter feed with PHP and JSON for API v1.1

First note: API 1.1 forces you to give authorization through oAuth meaning you’ll have to set up an app via Twitter Developers. Once you have on set up, you can follow along with the below code.

Second note: I slapped this together quickly, so test before using.

oAuth

I first create an authorization file, based off of zkniebel’s GitHub code. You’ll have to add in your own oAuth Access Tokens, Consumer Keys and Twitter handle. From there, things should work just fine.



$twitter_handle = "your own";

function buildBaseString($baseURI, $method, $params) {
    $r = array();
    ksort($params);
    foreach($params as $key=>$value){
        $r[] = "$key=" . rawurlencode($value);
    }
    return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}

function buildAuthorizationHeader($oauth) {
    $r = 'Authorization: OAuth ';
    $values = array();
    foreach($oauth as $key=>$value)
        $values[] = "$key=\"" . rawurlencode($value) . "\"";
    $r .= implode(', ', $values);
    return $r;
}

$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";

$oauth_access_token = "your own";
$oauth_access_token_secret = "your own";
$consumer_key = "your own";
$consumer_secret = "your own";

$oauth = array( 'oauth_consumer_key' => $consumer_key,
                'oauth_nonce' => time(),
                'oauth_signature_method' => 'HMAC-SHA1',
                'oauth_token' => $oauth_access_token,
                'oauth_timestamp' => time(),
                'oauth_version' => '1.0',
                'screen_name' => $twitter_handle);

$base_info = buildBaseString($url, 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;

// Make Requests
$header = array(buildAuthorizationHeader($oauth), 'Content-Type: application/json', 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
                  //CURLOPT_POSTFIELDS => $postfields,
                  CURLOPT_HEADER => false,
                  CURLOPT_URL => $url . '?screen_name=' . $twitter_handle,
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);



I recommend putting the above in a separate file and using an include_once() to bring it in with the below content. Or not, your choice.

Display the tweets

       

$decode = json_decode($json, true); //getting the file content as array

echo '<ul>';
foreach($decode as $tweet) {
    $tweet_text = $tweet["text"];
    echo '<li>';
    echo $tweet_text;
    echo '</li>';
}
echo '</ul>';

$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$reg_exHash = "/#([a-z_0-9]+)/i";
$reg_exUser = "/@([a-z_0-9]+)/i";

echo '<ul>';
foreach ($decode as $tweet) {
    $tweet_text = $tweet["text"]; //get the tweet
     
    // make links link to URL
    // http://css-tricks.com/snippets/php/find-urls-in-text-make-links/
    if(preg_match($reg_exUrl, $tweet_text, $url)) {

       // make the urls hyper links
       $tweet_text = preg_replace($reg_exUrl, "<a href='{$url[0]}'>{$url[0]}</a> ", $tweet_text);

    }

    if(preg_match($reg_exHash, $tweet_text, $hash)) {

       // make the hash tags hyper links    https://twitter.com/search?q=%23truth
       $tweet_text = preg_replace($reg_exHash, "<a href='https://twitter.com/search?q={$hash[0]}'>{$hash[0]}</a> ", $tweet_text);
       
       // swap out the # in the URL to make %23
       $tweet_text = str_replace("/search?q=#", "/search?q=%23", $tweet_text );

    }

    if(preg_match($reg_exUser, $tweet_text, $user)) {

        $tweet_text = preg_replace("/@([a-z_0-9]+)/i", "<a href='http://twitter.com/$1'>$0</a>", $tweet_text);

    }

    // display each tweet in a list item
    echo "<li>" . $tweet_text . "</li>";
} 
echo '</ul>';

Now, this is something I spliced together this morning after seeing they had finally killed v1.0, so it could probably stand to be improved upon. Take it with a grain of salt and test before you toss it into a live site.

I’ll have a better explanation later on.

Things to consider. Faster implementation, caching and code cleanup. Thoughts?

Subscribe
Notify of
guest
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Mary Somerville
Mary Somerville
7 years ago

This works well apart from your hash tags. It only picks up the first one in a tweet then overrides all others with it. My PHP skills aren’t good enough to figure out whats wrong. If you fix that bit it will be awesome!
Thanks for sharing it!

Mehul Bhandari
Mehul Bhandari
4 years ago

I have used same code but showing …

{“errors”:[{“code”:32,”message”:”Could not authenticate you.”}]}

Please Help !!

Terry Lipford
Terry Lipford
3 years ago

Thanks for the code snippet – and I was wondering if you might be able to give me a pointer. I scrape Twitter for tweets from my customer’s feed, and if I look on Twitter, there are occasionally images that are displayed with tweets but when I get the JSON stream from Twitter, there are no images in those tweets. And when I look closely at the [‘entities’][‘media’] area, there are no images for those tweets.

John Hartley is a Director of Product Engineering at Beam Dental in Columbus, OH. With 5+ years of leadership experience he has worked in startups, agencies, and began his career as a freelance Front End Developer. Always looking to iterate, this blog is a place for him to share his knowledge as well as hone his craft, challenge assumptions, and build a strong base of leadership and management knowledge. Connect with him on LinkedIn

3
0
Would love your thoughts, please comment.x
()
x