使用PHP和Twitter REST API获取关注者列表

时间:2014-10-31 12:55:50

标签: php twitter

我尝试使用以下代码获取关注者列表。此代码对于拥有数百个用户但未获得具有数千个用户的帐户的所有关注者的帐户是成功的。我可以做些什么来增强此代码?

<?php
    header('Content-type: text/html; charset=utf8');
    require_once('twitteroauth/twitteroauth.php');
        // consumer ve access
        $consumerkey = "CONSUMERKEY";
        $consumersecret = "CONSUMERSECRET";
        $accesstoken = "ACCESSTOKEN";
        $accesstokensecret = "ACCESSTOKENSECRET";

        // sınıfı başlatalım
        $connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret);

    // Empty array that will be used to store followers.
    $profiles = array();
    // Get the ids of all followers. Max. 5000
    $sc_name = 'mgocenoglu';
    $ids = $connection->get("https://api.twitter.com/1.1/followers/ids.json?screen_name=$sc_name");
    //print_r($ids->ids);
    // Chunk the ids in to arrays of 100.
    $ids_arrays = array_chunk($ids->ids, 100);
    //print_r($ids_arrays); 
    // Loop through each array of 100 ids.
    $i=1;
    foreach($ids_arrays as $implode) {
      // Perform a lookup for each chunk of 100 ids.
      $user_ids=implode(',', $implode);
      //echo $user_ids."<br>";
      $results = $connection->get("https://api.twitter.com/1.1/users/lookup.json?user_id=$user_ids");

      // Loop through each profile result.
      foreach($results as $profile) {
        //echo $i++."-".$profile->name." ".$profile->followers_count."<br>";
        $profiles[$profile->name] = $profile;
      }
    }
    //Sorting profiles according to followers count
    $sortArray = array();
    foreach($profiles as $person){ 
        foreach($person as $key=>$value){ 
            if(!isset($sortArray[$key])){ 
                $sortArray[$key] = array(); 
            } 
            $sortArray[$key][] = $value; 
        } 
    } 
    $orderby = "followers_count"; //change this to whatever key you want from the array 
    array_multisort($sortArray[$orderby],SORT_DESC,$profiles);
    ?>
    <html><body><table border=1>
    <?php
    foreach($profiles as $profile) {
        echo "<tr><td>".$i++."</td><td>".$profile->name."</td><td>".$profile->screen_name."</td><td>".$profile->followers_count."</td></tr>";
    }
    ?>
    </table></body></html>

1 个答案:

答案 0 :(得分:1)

//获取所有粉丝的ID。最大。 5000