Get Latest Twitter Status Easily with PHP
Recently I wanted to display my Last Tweet on a website, but you may have noticed that the old Twitter API v1.0 doesn't work anymore, the new update 1.1 requires authentication in order to interact with Twitter, which means there is no straight forward way of doing this without obtaining Twitter API keys.Getting Twitter API Keys
So, If you do not have Twitter application created, you need to create one here. Once it is created, click your application name and click "API Keys" tab on your application details page. There you should find all API key and API secret. If you scroll down a bit you will also see your Access Token and Secret.PHP library
Go to Github and download Abraham Williams's popular TwitterOAuth PHP library, this library is required to make HTTP requests to Twitter, we just need two files from twitteroauth folder from this library, just copy twitteroauth into your project.PHP Code
Here's the final code that goes into your website project. Copy your API Keys and replace values below where indicated.PHP
- 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
<?php
include_once('twitteroauth/twitteroauth.php');
$twitter_customer_key = 'JdmrAiQk2mx8v3tvhDEA';
$twitter_customer_secret = 'uQ7imQSv6hirqQr9Nt5mksCdUCVAfk5srF0Mk3vo';
$twitter_access_token = '17587879-mftRUoqaPQj2OLZdu2Y08qY9vHRJfM7hE2yo87Y3d';
$twitter_access_token_secret = 'jFQyQ64PAEnyBVCWYPgJdVEGr3X0RpoCldgkyLUW5A';
$connection = new TwitterOAuth($twitter_customer_key, $twitter_customer_secret, $twitter_access_token, $twitter_access_token_secret);
$my_tweets = $connection->get('statuses/user_timeline', array('screen_name' => 'saaraan', 'count' => 1));
echo '<div class="twitter-bubble">';
if(isset($my_tweets->errors))
{
echo 'Error :'. $my_tweets->errors[0]->code. ' - '. $my_tweets->errors[0]->message;
}else{
echo makeClickableLinks($my_tweets[0]->text);
}
echo '</div>';
//function to convert text url into links.
function makeClickableLinks($s) {
return preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a target="blank" rel="nofollow" href="$1" target="_blank">$1</a>', $s);
}
?>