Twitter API PHP Wiki

Hugo edited this page Jun 7, 2016 · 6 revisions

The following are example requests to make, assuming you have set up your settings array appropriately and have followed the instructions on this page correctly.

Basic Examples

Get a user's tweets

Official documentation: https://dev.twitter.com/rest/reference/get/statuses/user_timeline

$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$getfield = '?screen_name=j7mbo';
$requestMethod = 'GET';

$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getfield)
    ->buildOauth($url, $requestMethod)
    ->performRequest();

var_dump(json_decode($response));

Search global tweets for a hashtag

Official documentation: https://dev.twitter.com/docs/api/1.1/get/search/tweets

$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = '?q=#nerd';
$requestMethod = 'GET';

$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getfield)
    ->buildOauth($url, $requestMethod)
    ->performRequest();

var_dump(json_decode($response));

Delete a tweet

Official documentation: https://dev.twitter.com/docs/api/1.1/post/statuses/destroy/%3Aid

$url = 'https://api.twitter.com/1.1/statuses/destroy/YOURIDHERE.json';
$postfields = array('id' => 'YOURIDHERE');
$requestMethod = 'POST';

$twitter = new TwitterAPIExchange($settings);
$response =  $twitter->buildOauth($url, $requestMethod)
    ->setPostfields($postfields)
    ->performRequest();

var_dump(json_decode($response));

Searching using a geocode

Official documentation: https://dev.twitter.com/docs/api/1.1/get/search/tweets

$url = 'https://api.twitter.com/1.1/search/tweets.json';
$requestMethod = 'GET';

$getfield = '?q=test&geocode=37.781157,-122.398720,1mi&count=100';

$twitter = new TwitterAPIExchange($settings);
$response =  $twitter->setGetfield($getfield)
    ->buildOauth($url, $requestMethod)
    ->performRequest();

var_dump(json_decode($response));

Advanced Examples

Search for multiple users, multiple hashtags

Official documentation: https://dev.twitter.com/docs/using-search

$url = 'https://api.twitter.com/1.1/search/tweets.json';
$requestMethod = 'GET';

$getfield = '?q=#hashtag1+OR+#hashtag2+from:username1+OR+from:username2';

$twitter = new TwitterAPIExchange($settings);
$response =  $twitter->setGetfield($getfield)
    ->buildOauth($url, $requestMethod)
    ->performRequest();

var_dump(json_decode($response));