如何获得3,200条推文(Twitter API 1.1)

5 php twitter curl twitter-oauth

经过大量的试验和错误,我终于设法使用Twitters新API(版本1.1)获取推文.我正在使用PHP TwitterOauth库.虽然我能够获取推文,但有两件事我不明白.

  1. status/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++;
   } 
}
Run Code Online (Sandbox Code Playgroud)

更新:在尝试下面的queremys建议后,我想出了一个非常难看的"解决方案",它有几个主要的缺点.至少它显示了最多3,200条推文(以及一些重复).如果有问题的推特账号少于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++;
    }
}
Run Code Online (Sandbox Code Playgroud)

K-G*_*Gun 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;
}
Run Code Online (Sandbox Code Playgroud)

更新!

您需要 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;
Run Code Online (Sandbox Code Playgroud)