我遇到了一个问题,想知道如何返回Twitter上使用主题标签的总次数。在过去,我使用了以下代码,但是“http://search.twitter.com/search.json”地址已经被Twitter淘汰了。旧代码是:
<?php
global $total, $hashtag;
//$hashtag = '#supportvisitbogor2011';
$hashtag = '#MyHashtag';
$total = 0;
function getTweets($hash_tag, $page) {
global $total, $hashtag;
$url = 'http://search.twitter.com/search.json?q='.urlencode($hash_tag).'&';
$url .= 'page='.$page;
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
$json = curl_exec ($ch);
curl_close ($ch);
//echo "<pre>";
//$json_decode = json_decode($json);
//print_r($json_decode->results);
$json_decode = json_decode($json);
$total += count($json_decode->results);
if($json_decode->next_page){
$temp = explode("&",$json_decode->next_page);
$p = explode("=",$temp[0]);
getTweets($hashtag,$p[1]);
}
}
getTweets($hashtag,1);
echo $total;
?>
我知道您必须使用授权的Twitter应用程序并且能够获取数据。我能够设置应用程序,我可以使用以下代码提取数据列表,但我不确定如何使用该数据来计算总数。有人可以帮助我通过更改我的代码或帮助我如何去做它来获得总数。这是我的代码,用于提取主题标签数据:
<?php
session_start();
require_once("twitteroauth.php"); //Path to twitteroauth library
$hashtag = "MyHashtag";
$consumerkey = "MYINFOWOULDBEHERE";
$consumersecret = "MYINFOWOULDBEHERE";
$accesstoken = "MYINFOWOULDBEHERE";
$accesstokensecret = "MYINFOWOULDBEHERE";
function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return $connection;
}
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
$tweets = $connection->get("https://api.twitter.com/1.1/search/tweets.json?q=".$hashtag);
echo json_encode($tweets);
?>
答案 0 :(得分:3)
以下是this制作的Twitter 1.1 API的一个示例。记住这一点:
请注意Twitter的搜索服务,并且,通过扩展, 搜索API并不是Tweets的详尽来源。 不是全部 推文将通过搜索界面编入索引或提供。
https://dev.twitter.com/docs/api/1.1/get/search/tweets
twitter_search.php
(在 twitter-api-php 的同一文件夹中)twitter_search.php
twitter_search.php:
<?php
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"
);
/** Note: Set the GET field BEFORE calling buildOauth(); **/
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$requestMethod = 'GET';
$hashtag = 'twitterapi';
$getfield = '?q=%23'.$hashtag.'&result_type=recent&include_entities=true&count=100';
// Perform the request
$twitter = new TwitterAPIExchange($settings);
$json_output = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
// Let's calculate how many results we got
$json = json_decode($json_output);
$n = count($json->statuses);
echo $n;
?>