如何为Twitter API使用游标?
我写了一个PHP脚本,我希望在其中获取所有Twitter粉丝。但是在哪里放置游标?当我用1000个粉丝进行测试时,它可以正常工作,但是当关注者的数量超过6000或10000时,它最多只能获得5000个ID。
我想获取所有关注者,在哪里放置游标?我的代码是:
<?php
ini_set('max_execution_time', 600);
ini_set('memory_limit', '1024M');
require_once('twitteroauth.php');
$consumerKey = 'key1';
$consumerKeySecret = 'key2';
$accessToken = 'key3';
$accessTokenSecret = 'key4';
$cursor = -1; // first page
while( $cursor != 0 ){
$connection = new TwitterOAuth($consumerKey, $consumerKeySecret, $accessToken, $accessTokenSecret);
$profiles = array();
$sc_name = 'LarryWentz';
$cursor = "&cursor=" + $cursor;
$ids = $connection->get("https://api.twitter.com/1.1/friends/ids.json?screen_name=$sc_name".$cursor);
$cursor = $ids->next_cursor;
if(!is_array($ids->ids)) break;
$ids_arrays = array_chunk($ids->ids, 100);
$i=1;
foreach($ids_arrays as $implode) {
$user_ids=implode(',', $implode);
$results = $connection->get("https://api.twitter.com/1.1/users/lookup.json?user_id=$user_ids");
foreach($results as $profile) {
$profiles[$profile->name] = $profile;
}
}
}
foreach($profiles as $profile)
{
echo $i. "-" .$profile->name . "<br />";
$i++;
}
?>
答案 0 :(得分:4)
假设您使用此库https://github.com/abraham/twitteroauth:
$profiles = array();
$sc_name = 'LarryWentz';
$cursor = -1;
while ($cursor != 0) {
$ids = $connection->get("friends/ids", array("screen_name" => $sc_name, "cursor" => $cursor));
$cursor = $ids->next_cursor;
$ids_arrays = array_chunk($ids->ids, 100);
foreach($ids_arrays as $implode) {
$user_ids=implode(',', $implode);
$results = $connection->get("users/lookup.json", array("user_id" => $user_ids));
foreach($results as $profile) {
$profiles[$profile->name] = $profile;
}
}
}
答案 1 :(得分:1)
结果以 5,000 个用户ID的组给出,并且可以通过在后续请求中使用next_cursor值来导航结果的多个“页面”。有关更多信息,请参阅使用游标导航集合。 - 来自https://dev.twitter.com/rest/reference/get/friends/ids
这就是为什么你得到max 5000的结果,你必须使用光标。你必须把你的代码放在这样的循环中: 以下是您需要对光标执行的操作:
...
<?php
ini_set('max_execution_time', 600);
ini_set('memory_limit', '1024M');
require_once('twitteroauth.php');
$consumerKey = 'k1';
$consumerKeySecret = 'k2';
$accessToken = 'k3';
$accessTokenSecret = 'k4';
$cursor = -1; // first page
$profiles = array();
while( $cursor != 0 ){
$connection = new TwitterOAuth($consumerKey, $consumerKeySecret, $accessToken, $accessTokenSecret);
$sc_name = 'savanpaun';
$cursor = "&cursor=" + $cursor;
$ids = $connection->get("https://api.twitter.com/1.1/friends/ids.json?screen_name=$sc_name".$cursor);
$cursor = $ids->next_cursor;
if(!is_array($ids->ids)) break;
$ids_arrays = array_chunk($ids->ids, 100);
$i=1;
foreach($ids_arrays as $implode) {
$user_ids=implode(',', $implode);
$results = $connection->get("https://api.twitter.com/1.1/users/lookup.json?user_id=$user_ids");
foreach($results as $profile) {
$profiles[$profile->name] = $profile;
}
}
}
foreach($profiles as $profile)
{
echo $i. "-" .$profile->name . "<br />";
$i++;
}
?>
应该这样做!