Переполнение стека в курсоре API Twitter

У меня уже есть скрипт, который собирает первые 5000 пользователей из друзей / идентификаторов.
Я хочу собрать всех друзей, поэтому мне нужно перемещаться по курсорам, чтобы получить их. Я думаю, что понимаю, как работает курсор, но все же я не могу заставить его работать. Я пытаюсь присоединиться к next_cursor, но не знаю, что я делаю не так.

Кажется, курсор, который я пытаюсь получить, не правильно вызван.

Хотелось бы получить обратную связь с ними, потому что API Twitter не дает реального примера.

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

?>

1

Решение

Попробуйте этот код. Это принесет до 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 counterwhile ($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');
0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector