0

I'm trying to get the followers count from X user on Twitter using the API Version 1.1

The code I'm using works fine. What I need is a function to get the specific data I need from the data Twitter is giving me. In this case I need ['followers_count'].

This is PHP the code:

<?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>";    

?>

This is what I get from 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] => 
        )

)
1
  • Yes, that JSON response contains what you need, followers_count. So, decode it with json_decode and look in the object/array you get? What you get if you print_r($twitter_data);? Edit it into your question please.
    – halfer
    Jan 15, 2015 at 23:38

1 Answer 1

2

I should have shown you how to format the print_r(), so the output is (much!) more readable. Here is how to do it.

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

Anyway, from your output, it looks like you can just do this:

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

It is important to understand how this can be worked out from this debugging. Firstly the output of the print_r indicates the returned object is an array, and the first entry is a zero index, which looks like it is listing search results (it basically is).

The 0th item is an object (it is a stdClass) and is not an array, so the thing to be retrieved needs to be looked up with the reference -> operator rather than an array index. My guess is all items of data per search result can be looked up as a property value of this object.

As an aside, you'll notice that some items within this object are also objects. You can look those up using another reference, e.g.:

$twitter_data[0]->entities->url;
4
  • Thank you @halfer, I add: $followers_count = $twitter_data[0]['followers_count']; And get this: Fatal error: Cannot use object of type stdClass as array in
    – Peter
    Jan 16, 2015 at 0:00
  • No worries @user3307502. I've removed the answer from your question, as we like the Q&A format to be maintained here. You can always add your own answer to your own questions, but I don't think it is necessary in this case - it is contained in my answer.
    – halfer
    Jan 16, 2015 at 0:37
  • Also, it is really worth reading up on array and object structures. Given a print_r() output, it is often necessary to examine it and to determine what set of symbols would be required to look up a particular item.
    – halfer
    Jan 16, 2015 at 0:39
  • 1
    I will read more about array and structures. Thank you again!.
    – Peter
    Jan 16, 2015 at 0:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.