
In the footer of this website, I show my latest tweet. Until now I had been using Twitter API 1.0. Today Twitter stopped service for API 1.0 and I had to scramble to fix it so that it would work with Twitter API 1.1 (turns out it’s a lot more complicated). Here is the code I ended up using in case anyone needs it.
Do This First
Go to dev.twitter.com and create an app. This will provide you with the credentials you need to access your Twitter feed.
Credits
Hats off to Rivers from this article on Stack Overflow who really figured this one out. All I did was modify it to echo out each Tweet (I also set it to use only one tweet).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
<?php 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_token"; $oauth_access_token_secret = "your_token_secret"; $consumer_key = "your_consumer_key"; $consumer_secret = "your_consumer_secret"; $oauth = array( 'oauth_consumer_key' => $consumer_key, 'count' => 1, 'oauth_nonce' => time(), 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_token' => $oauth_access_token, 'oauth_timestamp' => time(), 'oauth_version' => '1.0'); $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), 'Expect:'); $options = array( CURLOPT_HTTPHEADER => $header, //CURLOPT_POSTFIELDS => $postfields, CURLOPT_HEADER => false, CURLOPT_URL => $url . '?count=1', CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false); $feed = curl_init(); curl_setopt_array($feed, $options); $json = curl_exec($feed); curl_close($feed); $twitter_data = json_decode($json); foreach($twitter_data as $t){ $the_tweet = "{$t->text}"; $the_tweet = preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1" target="_blank">$1</a>', $the_tweet); //echo "Username: {$t->from_user_name}"; echo "$the_tweet"; } ?> |
Do you find this snippet helpful? Have questions or suggestions? Let me know.
photo credit: mkhmarketing via photopin cc