在php,Api 1.1中获取推特趋势主题列表

时间:2017-11-09 11:28:04

标签: php twitter

我想获得最重要的趋势列表10或30,世界和地点,例如基辅或伦敦等。我尝试了this

https://api.twitter.com/1.1/trends/place.json
https://api.twitter.com/1.1/trends/place.json?id=1

和结果;

{
  "errors": [
    {
      "code": 215,
      "message": "Bad Authentication data."
    }
  ]
}

请在php中帮助解决这个问题,不要使用其他资源,版本1.1 api!

1 个答案:

答案 0 :(得分:1)

我做了;

<?php
error_reporting(0);
$twitterurl = "https://api.twitter.com/1.1/trends/place.json";

$oauth_access_token = "XXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$oauth_access_token_secret ="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$consumer_key = "XXXXXXXXXXXXXXXXXXXXXXXXX";
$consumer_secret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

$woeid='1';

/*
 * World=   1
*/

$oauth = array( 'oauth_consumer_key' => $consumer_key, 'oauth_nonce' => time(),'id' => $woeid, 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_nonce' => time(),'oauth_token' => $oauth_access_token, 'oauth_timestamp' => time(), 'oauth_version' => '1.0');

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;
}

$base_info = buildBaseString($twitterurl, 'GET', $oauth);
$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 => $twitterurl . "?id=$woeid",
    CURLOPT_RETURNTRANSFER => true,

    CURLOPT_SSL_VERIFYPEER => false);

$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$trends = json_decode($json,true);

//print_r($json); //if u see all data add$trend up line  $trends =json_decode($json);  and delete this line down lines change  !


$arrtrends=array();
for($i=0;$i<10;$i++){
    $arrtrends[]=$trends[0][trends][$i][name];
}
$locationname=$trends[0][locations][0][name];

//
print_r($arrtrends);
echo "Location: $locationname";