繁体   English   中英

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

[英]How to get the 3,200 tweets (Twitter API 1.1)

经过大量的试验和错误,我终于设法使用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++;
   } 
}

更新:在尝试下面的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++;
    }
}

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

$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;
}

UPDATE!

你需要使$max_id继续循环,并需要$max_id NULL来打破循环。

// 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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM