5

经过大量的反复试验,我终于设法使用 Twitter 的新 API(1.1 版)获取推文。我正在使用 PHP TwitterOauth 库。尽管我能够获取推文,但有两件事我不明白。

  1. statuses/user_timeline 的限制是 200 条推文。如何遍历结果以获取最大数量的 3,200 条推文?我读过一些关于发出多个 GET 请求的内容,但我不知道该怎么做。

  2. 似乎获取的推文数量是随机变化的,实际上很少达到参数“count”中指定的数量。这是为什么?

我的应用程序只是让访问者输入用户名并获取该用户的推文。这是我的代码。

if (isset($_GET['user'])) {
   $user = $_GET['user'];
   $content = $connection->get("statuses/user_timeline", array('count' => 200, 'exclude_replies' => true, 'screen_name' => $user));?>

   $j = 0;
   foreach ($content as $tweet) {
      echo $j.' '.$tweet->text. '<br />';
      $j++;
   } 
}

更新:在尝试了下面的 queremys 建议后,我想出了一个看起来非常难看的“解决方案”,它有几个主要缺点。至少它显示了最多 3,200 条推文(和一些重复)。如果相关 Twitter 帐户的推文少于 3,200 条,结果会看起来很奇怪。无论如何,只是想如果它可以激发灵感,我会分享它。

if (isset($_GET['user'])) {
    $user = $_GET['user'];

    $content = $connection->get('statuses/user_timeline', array(
    'count' => 200, 'exclude_replies' => true, 'screen_name' => $user, 'include_rts' => 1
));

    $x = 0;
    while ($x < 15) {
        $text = array();

        foreach ($content as $tweet) {
            $text[] = $tweet->id_str;
            echo $tweet->text.'<br />';
        }

        $last_tweet = end($text);

        $content = $connection->get('statuses/user_timeline', array(
    'count' => 200, 'exclude_replies' => true, 'screen_name' => $user, 'include_rts' => 1, 'max_id' => $last_tweet
));
        foreach ($content as $tweet) {
            echo $tweet->text.'<br />';
        }
        $x++;
    }
}
4

1 回答 1

2

它可能有点贵,但我认为可能(你可以测试类似的东西);

$contents = array();
$limit = 3200;
$max_id = null;
for ($count = 200; $count < $limit; $count += 200) {
    if (null !== $max_id && $max_id == '') {
        break;
    }

    $content = $connection->get('statuses/user_timeline', array(
        'count' => $count, 'exclude_replies' => true, 'screen_name' => $user,
        'max_id' => $max_id
    ));
    $contents[] = $content;
    // this indicates the last index of $content array
    $max_id = $content[count($content) - 1]->id_str;
}

更新!

您需要 make$max_id来继续循环,并且需要$max_idNULL 来中断循环。

// option 1, makes $max_id NULL silently
@ $max_id = $content[count($content) - 1]->id_str;

// option 2, search for last index of array
if (count($content)) {
    $last_tweet = end($content);
    $max_id = $last_tweet->id_str;
} else $max_id = null;
于 2013-01-20T22:05:41.600 回答