duanchuang1935 2017-04-26 07:41
浏览 83

Twitter API游标PHP

Already I have a script that collects the first 5000 users from friends/ids. I want to collect all friends so I have to move through cursors to get them. I think I understand the way the cursor works but still I'm not able to make it work. I'm trying to acceed to next_cursor but don't know what I'm doing wrong.

It seems like the cursor I'm trying to get isn't properly called.

Would like some feedback with these because twitter's API doesn't give any real example.

<?php

header("Content-Type: text/html;charset=utf-8");
ini_set('display_errors', 1);
require_once('TwitterAPIExchange.php');
session_start();
$user = $_POST['nombre'];
$_SESSION['user']=$_POST['nombre'];
$usuario = $user;


$servername = "localhost";
$username = "root";
$password = "";
$dbname = "twitter";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 


/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
 'oauth_access_token' => "k1",
'oauth_access_token_secret' => "k2",
'consumer_key' => "k3",
'consumer_secret' => "k4"

);

//https://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=microsoft

$cursor = "cursor=".-1;
$url = 'https://api.twitter.com/1.1/friends/ids.json';
$getfield = '?'.$cursor.'screen_name='.$usuario;
$requestMethod = 'GET';


$twitter = new TwitterAPIExchange($settings);
$json = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(true, array(CURLOPT_CAINFO => dirname(__FILE__) . '/cacert.pem'));

$arrayFriends = json_decode($json, true,512,JSON_BIGINT_AS_STRING);

echo 'Usuario' .";". 'Nombre'.";".'Location'.";".'Numero Amigos'.";".'Numero     followers'.";".'Descripcion'."
";

foreach($arrayFriends['next_cursor'] as $curs){
foreach($arrayFriends['ids'] as $obj){
while($cursor != 0){
    //$cursor->$arrayFriends['ids']->next_cursor;
    $cursor = $curs;
    //$cursor = "&cursor=" + $cursor; 
    $sql = "INSERT INTO friends (user, id) VALUES ('$usuario','$obj')";
    if ($conn->query($sql) === TRUE) {
        //echo "New record created successfully";
        header("Location:logic.php");
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}
  }
}
$conn->close();

?>
  • 写回答

1条回答 默认 最新

  • douye5949 2017-08-11 16:43
    关注

    Try this code. It will fetch upto 3000 friends.

    Running time of the script is approx 3-5 minutes

    //function to fetch friends of the authenticating user
    
    function getAllFriends($auth_user_screen_name)
    {
        //---getting application tokens and connection to database
       $arraySettings = defaultSettings();
    
      $con = $arraySettings['connection'];
    
      //create api instance
       \Codebird\Codebird::setConsumerKey('consumerKey', 'consumerSecret');
       $objTwitter = \Codebird\Codebird::getInstance();
    
       $oauth_token = "oauth_token";
       $oauth_token_secret = "oauth_token_secret";
    
       $objTwitter->setToken($oauth_token, $oauth_token_secret);
    
       //initialize empty array to store friends data returned from API     
       $friendsData=array();
    
      if (strlen($oauth_token) > 0 && strlen($oauth_token_secret) > 0) {
    
        $cursor = -1;
        $j=0;
        while ($cursor != 0)
        {
            $params = array(
                'screen_name' => $auth_user_screen_name,
                'count' => 200,
                'cursor' => $cursor
            );
    
            $json = $objTwitter->friends_list($params);
            $httpStatus = $json->httpstatus;
    
            $jsonFriends=(array)$json;
    
            //meta is user defined key 
            $friendsData['meta']['remaining']=$jsonFriends['rate']['remaining'];
            $friendsData['meta']['seconds_to_reset']=($jsonFriends['rate']['reset'] - time());
    
            if ($httpStatus == 200) {
    
                echo "remaining requests " . $jsonFriends['rate']['remaining'] . '<br>';
                echo "next reset after (sec) " . ($jsonFriends['rate']['reset'] - time()) . '<br>';
    
                $lenght = count($jsonFriends['users']);
    
                $cursor = $jsonFriends['next_cursor'];
                echo "next_cursor=>" . $cursor . "<br>";
    
                $i = 0;  //loop counter
    
    
                while ($i < $lenght) {
    
                    $friendsData[$j]['screen_name']=$profileScreenName = $jsonFriends['users'][$i]->screen_name;
                    $friendsData[$j]['name']=$profileFullName = $jsonFriends['users'][$i]->name;
                    $friendsData[$j]['location']=$profileLocation = $jsonFriends['users'][$i]->location;
                    $friendsData[$j]['description']=$profileDescription = $jsonFriends['users'][$i]->description;
                    $friendsData[$j]['followers_count']=$followersCount = $jsonFriends['users'][$i]->followers_count;
                    $friendsData[$j]['friends_count']=$friendsCount = $jsonFriends['users'][$i]->friends_count;
    
                    $friendsData['']=$language = $jsonFriends['users'][$i]->lang;
                    $friendsData['']=$profileTwitterId = $jsonFriends['users'][$i]->id;
                    $friendsData['']=$isVerified = $jsonFriends['users'][$i]->verified;
                    $friendsData['']=$joinDate = date('Y-m-d H:i:s', strtotime($jsonFriends['users'][$i]->created_at));
                    $friendsData['']=$userWebsiteUrl = $jsonFriends['users'][$i]->url;
                    $friendsData['']=$tweetsCount = $jsonFriends['users'][$i]->statuses_count;
    
                    $friendsData['']=$defaultProfileImage = $jsonFriends['users'][$i]->default_profile_image;
    
                    $friendsData['']=$favouritesCount = $jsonFriends['users'][$i]->favourites_count;
                    $friendsData['']=$isGeoEnabled = $jsonFriends['users'][$i]->geo_enabled;
                    $friendsData['']=$utcOffset = $jsonFriends['users'][$i]->utc_offset;
                    $friendsData['']=$timeZone = $jsonFriends['users'][$i]->time_zone;
    
    
                    $i++; //counter for friends in particular cursor
                    $j++; //counter for friends for all friends including all cursor requests
    
                }
    
            } else {
                   //if httpStatus other than 200
                $friendsData['meta']['error_code']=$errorCode = $jsonFriends['errors'][0]->code;
                $friendsData['meta']['error_message']=$errorMessage = $jsonFriends['errors'][0]->message;
    
    
                echo "<pre>";
                //print error and rate data
                print_r($friendsData['meta']); 
    
    
            }
            // check whether Api limit exceed
            if ($friendsData['meta']['remaining']==0)
            {
    
                echo "<br>please wait=>".$friendsData['meta']['seconds_to_reset']." seconds";
                break;
            }
    
        }
        echo "<pre>";
        print_r($friendsData); //print all friends data including errors if any
    
      }
    }
    
    
    //call function to fetch all friends 
    //only max 3000 friends will retrieved in single request
    getAllFriends('myUsername');
    
    评论

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图