問題描述
如何使用 PHP 獲取我的粉絲數.
How to get my followers count number with PHP.
我在這里找到了這個答案: Twitter 粉絲計數,但它不起作用,因為API 1.0 不再有效.
I found this answer here: Twitter follower count number, but it is not working because API 1.0 is no longer active.
我也嘗試過使用此 URL 的 API 1.1:https://api.twitter.com/1.1/users/lookup.json?screen_name=google 但顯示錯誤(錯誤的身份驗證數據).
I have also tried with API 1.1 using this URL: https://api.twitter.com/1.1/users/lookup.json?screen_name=google but is is showing an error(Bad Authentication data).
這是我的代碼:
$data = json_decode(file_get_contents('http://api.twitter.com/1.1/users/lookup.json?screen_name=google'), true);
echo $data[0]['followers_count'];
推薦答案
Twitter API 1.0 已棄用且不再處于活動狀態.使用 REST 1.1 API,您需要 oAuth 身份驗證才能從 Twitter 檢索數據.
Twitter API 1.0 is deprecated and is no longer active. With the REST 1.1 API, you need oAuth authentication to retrieve data from Twitter.
改用這個:
<?php
require_once('TwitterAPIExchange.php'); //get it from https://github.com/J7mbo/twitter-api-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"
);
$ta_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$getfield = '?screen_name=REPLACE_ME';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$follow_count=$twitter->setGetfield($getfield)
->buildOauth($ta_url, $requestMethod)
->performRequest();
$data = json_decode($follow_count, true);
$followers_count=$data[0]['user']['followers_count'];
echo $followers_count;
?>
在某些情況下,解析 XML 可能更容易.
Parsing the XML might be easier in some cases.
這是一個解決方案(經過測試):
<?php
$xml = new SimpleXMLElement(urlencode(strip_tags('https://twitter.com/users/google.xml')), null, true);
echo "Follower count: ".$xml->followers_count;
?>
希望這有幫助!
這篇關于Twitter 中的關注者數量的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!