Skip to content

Twitter API PHP Wiki

Daniele Bernardi edited this page Jan 8, 2019 · 7 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://developer.twitter.com/en/docs/tweets/timelines/api-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://developer.twitter.com/en/docs/tweets/search/api-reference/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://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id

$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://developer.twitter.com/en/docs/tweets/search/api-reference/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://developer.twitter.com/en/docs/tweets/search/guides/standard-operators

$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));