Twitter API调用间歇性失败

时间:2010-07-10 21:28:12

标签: php wordpress twitter http-get

我正在使用PHP来显示用户的最新推文。这是在Wordpress中。这在大多数情况下都有效 - 但有时,我会收到此错误:

  

file_get_contents(http://api.twitter.com/1/statuses/user_timeline/[username].json)[function.file-get-contents]:无法打开流:HTTP请求失败!第47行的[/] / twitter.php中的HTTP / 1.1 400错误请求

我绝对肯定我没有超过Twitter API限制,因为即使我的缓存代码存在缺陷,也没有其他人可以看到它 - 它在本地托管 - 而且我无法查看该页面150次一个小时内。我已经测试过确实正在检索用户名和数据库条目。这是我的代码:

<?php
function twitter($username) {
$tweet = '';
echo $username;
if (!get_option('twitter_last_updated')) {
    $format='json';
    $tweet_raw=file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$username}.{$format}");
    $tweet = json_decode($tweet_raw);
    add_option('twitter_last_updated', time(), "", "yes");
    add_option('twitter_last_updated_author', $username, "", "yes");
    add_option('twitter_last_updated_data', $tweet_raw, "", "yes");
} elseif (time() - get_option('twitter_last_updated') > 30 || get_option('twitter_last_updated_author') != $username) {
    $format='json';
 $tweet_raw=file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$username}.{$format}");
    $tweet = json_decode($tweet_raw);
    update_option('twitter_last_updated', time());
    update_option('twitter_last_updated_author', $username);
    update_option('twitter_last_updated_data', $tweet_raw);
} else {
$tweet = json_decode(get_option('twitter_last_updated_data'));
} ?>
<!-- display the tweet -->
<?php } ?>

我真的很感激这方面的一些帮助。我觉得完全难过。

4 个答案:

答案 0 :(得分:2)

首先,您不应该使用file_get_contents通过网络检索“文件”。你应该使用curl。它可能只是系统响应延迟,或者Twitter发布重定向以实现负载平衡。 file_get_contents不遵循重定向,并且基本上会立即超时。如果没有指定超时,可以将Curl设置为遵循重定向并遵守网络超时(我认为1分钟)。最重要的是,卷曲可以说明它失败的原因。

答案 1 :(得分:1)

你多久调用一次这个函数?如果我没记错的话,Twitter最近将每小时的最大通话量从每小时150改为75。您可能希望缓存结果,以免耗尽您的津贴。

请参阅此slashdot故事:Twitter Throttling hits 3rd party apps

答案 2 :(得分:0)

为什么不使用WordPress HTTP API?这正是它的设计目标 - 使用标准WordPress函数处理HTTP的包装器,无论平台或设置如何。

答案 3 :(得分:0)

我写了类似于你所拥有的东西并且它像每3个请求一样失败,解决方案是在file_get_contents上构建一个小缓存系统和@,以避免php向用户抛出错误。

当twitter失败时,它会失败很多,你只需从之前构建的缓存中获取数据。

我也不建议你添加这个onfly,因为twitter问题,它可能会减慢整个页面的构建速度。