如何在 Twitter API 1.1 中获取关注者数量?

How to obtain follower count in Twitter API 1.1?

我正在尝试使用 API 版本 1.1

获取 Twitter 上 X 用户的关注者数量

我使用的代码工作正常。我需要的是从 Twitter 给我的数据中获取我需要的特定数据的功能。在这种情况下,我需要 ['followers_count'].

这是PHP代码:

<?php
$token = '*';
$token_secret = '*';
$consumer_key = '*';
$consumer_secret = '*';

$host = 'api.twitter.com';
$method = 'GET';
$path = '/1.1/users/lookup.json'; // api call path


$query = array( // query parameters
    'screen_name' => 'ArianaGrande',
    'count' => '5'
);

$oauth = array(
    'oauth_consumer_key' => $consumer_key,
    'oauth_token' => $token,
    'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended
    'oauth_timestamp' => time(),
    'oauth_signature_method' => 'HMAC-SHA1',
    'oauth_version' => '1.0'
);

$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);

$arr = array_merge($oauth, $query); // combine the values THEN sort

asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)

// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));

$url = "https://$host$path";

// mash everything together for the text to hash
$base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);

// same with the key
$key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);

// generate the hash
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));

// this time we're using a normal GET query, and we're only encoding the query params
// (without the oauth params)
$url .= "?".http_build_query($query);
$url=str_replace("&amp;","&",$url); //Patch by @Frewuill

$oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
ksort($oauth); // probably not necessary, but twitter's demo does it

// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$oauth = array_map("add_quotes", $oauth);

// this is the full value of the Authorization line
$auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));

// if you're doing post, you need to skip the GET building above
// and instead supply query parameters to CURLOPT_POSTFIELDS
$options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
                  //CURLOPT_POSTFIELDS => $postfields,
                  CURLOPT_HEADER => false,
                  CURLOPT_URL => $url,
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_SSL_VERIFYPEER => false);

// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);

$twitter_data = json_decode($json, true);

echo "<pre>" . print_r($twitter_data, true) . "</pre>";    

?>

这是我从推特上得到的:

Array
(
    [0] => stdClass Object
        (
            [id] => 34507480
            [id_str] => 34507480
            [name] => Ariana Grande
            [screen_name] => ArianaGrande
            [location] => Honeymoon ave. 
            [profile_location] => 
            [description] => 
            [url] => http://t.co/eUeupXB0LS
            [entities] => stdClass Object
                (
                    [url] => stdClass Object
                        (
                            [urls] => Array
                                (
                                    [0] => stdClass Object
                                        (
                                            [url] => http://t.co/eUeupXB0LS
                                            [expanded_url] => http://smarturl.it/ArianaMyEvrythnDlxDA
                                            [display_url] => smarturl.it/ArianaMyEvryth…
                                            [indices] => Array
                                                (
                                                    [0] => 0
                                                    [1] => 22
                                                )

                                        )

                                )

                        )

                    [description] => stdClass Object
                        (
                            [urls] => Array
                                (
                                )

                        )

                )

            [protected] => 
            [followers_count] => 23781983
            [friends_count] => 68420
            [listed_count] => 45204
            [created_at] => Thu Apr 23 02:56:31 +0000 2009
            [favourites_count] => 13627
            [utc_offset] => -28800
            [time_zone] => Pacific Time (US & Canada)
            [geo_enabled] => 
            [verified] => 1
            [statuses_count] => 35968
            [lang] => en
            [status] => stdClass Object
                (
                    [created_at] => Thu Jan 15 02:15:45 +0000 2015
                    [id] => 555548863310753794
                    [id_str] => 555548863310753794
                    [text] => god I love her @theellenshow http://t.co/kSCFRd6sBZ
                    [source] => Twitter for iPad
                    [truncated] => 
                    [in_reply_to_status_id] => 
                    [in_reply_to_status_id_str] => 
                    [in_reply_to_user_id] => 
                    [in_reply_to_user_id_str] => 
                    [in_reply_to_screen_name] => 
                    [geo] => 
                    [coordinates] => 
                    [place] => 
                    [contributors] => 
                    [retweet_count] => 11194
                    [favorite_count] => 20529
                    [entities] => stdClass Object
                        (
                            [hashtags] => Array
                                (
                                )

                            [symbols] => Array
                                (
                                )

                            [user_mentions] => Array
                                (
                                    [0] => stdClass Object
                                        (
                                            [screen_name] => TheEllenShow
                                            [name] => Ellen DeGeneres
                                            [id] => 15846407
                                            [id_str] => 15846407
                                            [indices] => Array
                                                (
                                                    [0] => 15
                                                    [1] => 28
                                                )

                                        )

                                )

                            [urls] => Array
                                (
                                    [0] => stdClass Object
                                        (
                                            [url] => http://t.co/kSCFRd6sBZ
                                            [expanded_url] => http://ellentube.com/videos/0-ma4x1e5a/
                                            [display_url] => ellentube.com/videos/0-ma4x1…
                                            [indices] => Array
                                                (
                                                    [0] => 29
                                                    [1] => 51
                                                )

                                        )

                                )

                        )

                    [favorited] => 
                    [retweeted] => 
                    [possibly_sensitive] => 
                    [lang] => en
                )

            [contributors_enabled] => 
            [is_translator] => 
            [is_translation_enabled] => 1
            [profile_background_color] => 000000
            [profile_background_image_url] => http://pbs.twimg.com/profile_background_images/455946880426328064/EZaaKmcF.png
            [profile_background_image_url_https] => https://pbs.twimg.com/profile_background_images/455946880426328064/EZaaKmcF.png
            [profile_background_tile] => 1
            [profile_image_url] => http://pbs.twimg.com/profile_images/554080800665112577/1AyXEQSF_normal.jpeg
            [profile_image_url_https] => https://pbs.twimg.com/profile_images/554080800665112577/1AyXEQSF_normal.jpeg
            [profile_banner_url] => https://pbs.twimg.com/profile_banners/34507480/1399852554
            [profile_link_color] => AD92D1
            [profile_sidebar_border_color] => 000000
            [profile_sidebar_fill_color] => F6F6F6
            [profile_text_color] => D8A0C1
            [profile_use_background_image] => 1
            [default_profile] => 
            [default_profile_image] => 
            [following] => 
            [follow_request_sent] => 
            [notifications] => 
        )

)

我应该向您展示如何设置 print_r() 的格式,以便输出(更!)更易读。以下是操作方法。

echo "<pre>" . print_r($twitter_data, true) . "</pre>";

无论如何,从你的输出来看,你似乎可以这样做:

$followers_count = $twitter_data[0]->followers_count;

重要的是了解如何通过调试解决这个问题。首先 print_r 的输出表明返回的对象是一个数组,第一个条目是一个零索引,看起来像是在列出搜索结果(基本上是)。

第 0 项是一个对象(它是一个 stdClass)而不是一个数组,所以要检索的东西需要用引用 -> 运算符而不是一个数组来查找数组索引。我的猜测是每个搜索结果的所有数据项都可以作为该对象的 属性 值进行查找。

顺便说一句,您会注意到此对象中的某些项目也是对象。您可以使用其他参考资料进行查找,例如:

$twitter_data[0]->entities->url;