【问题标题】:How to obtain follower count in Twitter API 1.1?如何在 Twitter API 1.1 中获取关注者数量?
【发布时间】:2015-03-14 12:21:44
【问题描述】:

我正在尝试使用 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>";    

?>

这是我从 Twitter 得到的:

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] => 
        )

)

【问题讨论】:

  • 是的,该 JSON 响应包含您需要的内容,followers_count。那么,使用json_decode 对其进行解码并查看你得到的对象/数组?如果你print_r($twitter_data);,你会得到什么?请把它编辑成你的问题。

标签: php json twitter twitter-oauth


【解决方案1】:

我应该向您展示如何格式化print_r(),因此输出(更多!)更具可读性。这是怎么做的。

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

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

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

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

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

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

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

【讨论】:

  • 谢谢@halfer,我补充说:$followers_count = $twitter_data[0]['followers_count'];并得到这个:致命错误:不能在中使用stdClass类型的对象作为数组
  • 不用担心@user3307502。我已从您的问题中删除了答案,因为我们喜欢在此处保留问答格式。您可以随时为自己的问题添加自己的答案,但我认为在这种情况下没有必要 - 它包含在我的答案中。
  • 另外,关于数组和对象结构真的值得一读。给定print_r() 输出,通常需要检查它并确定查找特定项目需要哪些符号集。
  • 我将阅读有关数组和结构的更多信息。再次感谢您!。
猜你喜欢
  • 2013-07-01
  • 2013-06-11
  • 1970-01-01
  • 2010-12-23
  • 1970-01-01
  • 2020-12-22
  • 2012-07-20
  • 2021-11-25
  • 1970-01-01
相关资源
最近更新 更多