2017-04-26 64 views
1

我已经有一个脚本,收集来自朋友/ ids的前5000个用户。 我想收集所有的朋友,所以我必须通过游标移动来获取它们。我想我理解光标的工作方式,但仍无法使其工作。我试图接受next_cursor,但不知道我做错了什么。Twitter API游标PHP

这似乎是我试图得到的游标没有正确调用。

想与这些反馈,因为twitter的API没有给出任何实际的例子。

<?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'."\n"; 

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(); 

?> 
+0

嗨,有人可以给我一点的反馈。我试图解决这个问题,但是在这个问题上浪费了很多时间。 – seyroku

+0

哟家伙,仍然不工作,需要建议或什么! – seyroku

+0

我正在共享使用光标提取所有朋友的代码。但是,这是一个很好的做法,可以一次性获取所有朋友。您仍然可以抓取3000个朋友,并允许每个请求提供15个请求/ 15分钟窗口和最多200个结果。 宁可next_cursor存储在数据库中,并从数据库中检索光标价值作出新的要求。你可以为此使用cron-job。 – prograshid

回答

0

试试看看这个代码。它将获得多达3000个朋友。

运行脚本的时间大约3-5分钟

//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');