【问题标题】:Twitter API - Fetching tweets fails to get tweets on occasionTwitter API - 获取推文有时无法获取推文
【发布时间】:2015-08-27 06:53:16
【问题描述】:

我有一个脚本,我在 PHP 中使用它来将推文写入文本文件并在我的网站上使用它们。我还设置了一个 cron 作业,它将每小时运行脚本并获取最新的推文。这有效并且设置正确。

但是,我注意到有时它无法获取任何推文并写入文件,将其保留为 0KB,因此我的客户打电话给我说它已损坏。

还有其他人在使用 twitter API 时遇到过这个问题吗?

这是脚本:

<?php
session_start();
require_once("twitteroauth-master/twitteroauth/twitteroauth.php");     
//Path to twitteroauth library
$twitteruser = "Username";
$notweets = 10;
$consumerkey = "****";
$consumersecret = "****";
$accesstoken = "*****";
$accesstokensecret = "*****";

function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
 $connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
 return $connection;
}

$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);

$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);

//Check twitter response for errors.
if ( isset( $tweets->errors[0]->code )) {
// If errors exist, print the first error for a simple notification.
echo "Error encountered: ".$tweets->errors[0]->message." Response code:" .$tweets->errors[0]->code;
} else {
// No errors exist. Write tweets to json/txt file.
$url = "/var/www/html/etc etc etc";
$file = $url.$twitteruser."-tweets.txt";
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, json_encode($tweets));
fclose($fh);

if (file_exists($file)) {
   echo $file . " successfully written (" .round(filesize($file)/1024)."KB)";
} else {
    echo "Error encountered. File could not be written.";
}
}
?>

【问题讨论】:

  • 你应该检查文件大小以及它的存在,然后var_dump()$tweets 的内容,看看里面有什么阻止 json_encode 工作。

标签: php twitter cron


【解决方案1】:

您的脚本是为打印错误消息而编写的。您应该调查该消息是什么。

如果您从 cron 运行它,您可以配置 cron 以捕获所有输出并通过电子邮件发送。

您还可以使用 error_log 函数或日志库更改脚本以记录输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-06
    • 2023-03-31
    • 2016-06-21
    • 1970-01-01
    • 2013-01-18
    • 2015-02-21
    • 2016-05-18
    • 2012-12-05
    相关资源
    最近更新 更多