Skip to content

Instantly share code, notes, and snippets.

@ValentinH
Created January 5, 2014 10:35
Show Gist options
  • Save ValentinH/8266635 to your computer and use it in GitHub Desktop.
Save ValentinH/8266635 to your computer and use it in GitHub Desktop.
How to query Twitter search API in PHP. This example shows how to query a hashtag and get the top 100 more recent results. * require CURL.
function queryTwitter($search)
{
$url = "https://api.twitter.com/1.1/search/tweets.json";
if($search != "")
$search = "#".$search;
$query = array( 'count' => 100, 'q' => urlencode($search), "result_type" => "recent");
$oauth_access_token = "ABCD";
$oauth_access_token_secret = "1234";
$consumer_key = "abcd";
$consumer_secret = "5678";
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0');
$base_params = empty($query) ? $oauth : array_merge($query,$oauth);
$base_info = buildBaseString($url, 'GET', $base_params);
$url = empty($query) ? $url : $url . "?" . http_build_query($query);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
return json_decode($json);
}
function buildBaseString($baseURI, $method, $params)
{
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth)
{
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
@latheva
Copy link

latheva commented May 11, 2018

Great job !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment