Get Twitter Latest Tweets Using API in PHP

In my previous article we have discussed about how to Facebook page feed using Graph API in php. Now we will see how to get latest twitter tweets using API in php.To get the latest tweets you must have an API Keys.
First of all we have to create a Twitter application from developer section and get required information to get tweets. Let us follow the given below steps to create a twitter application and get API Keys. Before proceeding we required Twitter OAuth PHP Library which can be downloading from Git Hub.
Steps to follow:
Sign in with Twitter Account here
Click on Create new App
Fill the website name and URL
Click on Create Button
On the next screen you will get details Click on Keys and Access Tokens Tab

Click on Create access tokens button and scroll down webpage
You will get Access Token and Access Token Secret

Access Token
Access Token

Put all the credential in given below snippet.

require_once("twitteroauth-master/twitteroauth/twitteroauth.php"); //Path to twitteroauth library you downloaded in step 3

$twitteruser = " "; //user name of twitter account
$notweets = 30; //no tweets you want to retrieve
$consumerkey = "Your consumer key"; 
$consumersecret = "Your consumer secret"; 
$accesstoken = "Access token you have got from above"; 
$accesstokensecret = "Access token secret"; 

function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
  $connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
  return $connection;

$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);

$tweets = $connection->get("".$twitteruser."&count=".$notweets);


$tweetsall = json_decode($p,true); //decodes the json string into an array

//display each tweets using foreach
foreach($tweetsall as $tweet)
echo $tweet['text']."<br />";
echo $tweet['created_at']."<br /><br />";


Leave a Reply

Your email address will not be published. Required fields are marked *