How to Use Twitter API with PHP
Twitter is an information network and communication mechanism that produces more than 200 million tweets a day. The Twitter platform offers API’s to access their data. Each API represents a facet of Twitter, and allows developers to build upon and extend their applications in new and creative ways. So using their you can built your custom app, J7mbo has developed a quick api access in PHP so that you can easily send GET and POST to Twitter and get latest tweet, treading topic etc.
Integrate Twitter API With PHP
Follow below steps by step tutorial to integrate Twitter API With PHP in simple way.
Step.1: Download TwitterAPIExchange.php class form here.
Step.2: Include the class in your PHP code.
require_once('TwitterAPIExchange.php');
Step.3: Create a twitter app on the twitter developer site and Enable read/write access for your twitter app.
Step.4: Grab your access tokens, access token secret, consumer_key and consumer_secret from the twitter developer site and place in your api settings to authenticate your request.
$settings = array( 'oauth_access_token' => "YOUR_OAUTH_ACCESS_TOKEN", 'oauth_access_token_secret' => "YOUR_OAUTH_ACCESS_TOKEN_SECRET", 'consumer_key' => "YOUR_CONSUMER_KEY", 'consumer_secret' => "YOUR_CONSUMER_SECRET" );
Step.5: Choose URL and Request Method. Then Perform the request!
Example for POST/PUT request
$url = 'https://api.twitter.com/1.1/blocks/create.json'; $requestMethod = 'POST'; $postfields = array( 'screen_name' => 'usernameToBlock', 'skip_status' => '1' ); $twitter = new TwitterAPIExchange($settings); echo $twitter->buildOauth($url, $requestMethod) ->setPostfields($postfields) ->performRequest();
GET Request Example
Set the GET field BEFORE calling buildOauth(); and everything else is the same:
$url = 'https://api.twitter.com/1.1/followers/ids.json'; $getfield = '?screen_name=J7mbo'; $requestMethod = 'GET'; $twitter = new TwitterAPIExchange($settings); echo $twitter->setGetfield($getfield) ->buildOauth($url, $requestMethod) ->performRequest();
By using above method I created a simple program to get live trending topic in INDIA.
<?php ini_set('display_errors', 1); require_once('TwitterAPIExchange.php'); /** Set access tokens here - see: https://dev.twitter.com/apps/ **/ $settings = array( 'oauth_access_token' => "YOUR_OAUTH_ACCESS_TOKEN", 'oauth_access_token_secret' => "YOUR_OAUTH_ACCESS_TOKEN_SECRET", 'consumer_key' => "YOUR_CONSUMER_KEY", 'consumer_secret' => "YOUR_CONSUMER_SECRET" ); $url = 'https://api.twitter.com/1.1/trends/place.json'; $getfield = '?id=23424848'; $requestMethod = 'GET'; $twitter = new TwitterAPIExchange($settings); echo $result = $twitter->setGetfield($getfield) ->buildOauth($url, $requestMethod) ->performRequest();
See live demo and download source code.
DEMO | DOWNLOAD