【发布时间】:2013-12-11 14:40:27
【问题描述】:
我目前正在编写一个通过 Twitter API 遍历用户时间线的 Web 应用程序。我在获取数据或操作数据方面没有任何问题。我遇到的问题是速度。 Twitter API 将您可以检索的推文数量限制为每页 200 条。分页是通过 ID 完成的,方法是在 (max_id) 中传递一个参数,这是您在上一页阅读的最后一条推文。有没有人能想到提高我收到这些推文的速度?我正在使用 abraham oauth lib。我的代码如下:
$twitteroauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $oauth['oauth_token'], $oauth['oauth_token_secret']);
$tweets = $twitteroauth->get('statuses/user_timeline', array ( 'screen_name' => 'user_name', 'count' => 200));
// get first batch of tweets from api
foreach($tweets as $t)
{
$tweets_to_process[] = $t;
}
// get last id of tweet and set prev_id to 0
$last_id = $tweets_to_process[count($tweets_to_process)-1]->id_str;
$prev_id = 0;
$loop_num = 0;
// loop through pages whilst last page returned of api result does not equal last of last result
while($last_id != $prev_id && $loop_num < 4)
{
// get tweets
$tweets = $twitteroauth->get('statuses/user_timeline', array ( 'screen_name' => 'user_name', 'count' => 200, 'max_id' => $last_id));
// loop through tweets and add to array
foreach($tweets as $t)
{
$tweets_to_process[] = $t;
}
// set prev and last id
$prev_id = $last_id;
$last_id = $tweets_to_process[count($tweets_to_process)-1]->id_str;
$loop_num ++;
}
正如你所看到的,我在 while 循环中放置了一个中断计数器,因为从用户体验的角度来看,循环最多 3200 条推文需要太长时间。
【问题讨论】: