处理错误file_get_contents

时间:2013-04-11 11:52:25

标签: php json twitter file-get-contents

我正在编写一个使用.php脚本来使用twitter搜索API获取推文的应用程序。 见下面的代码:

<?php
$hashtag = 'hashtag'; // We search Twitter for the hashtag
$show = 25; // And we want to get 25 tweets
// Local path
$cacheFile = '../../_data/tweets.json.cache'; // A cachefile will be placed in _data/


$json = file_get_contents("http://search.twitter.com/search.json?result_type=recent&rpp=$show&q=%23" . $hashtag. "%20-RT") or die("Could not get tweets");
$fp = fopen($cacheFile, 'w');
fwrite($fp, $json);
fclose($fp);
?>

我的问题是我想确保这个脚本运行没有失败,或者它确实失败至少不会保持循环。

脚本将每1分钟自动运行一次。 有谁知道在这里处理错误的好方法?

TL; DR:我如何处理代码错误?

1 个答案:

答案 0 :(得分:2)

简单来说,使用'@'前缀作为函数。它可以抑制显示错误。 Read More Here

<?php
$hashtag = 'hashtag'; // We search Twitter for the hashtag
$show = 25; // And we want to get 25 tweets
$cacheFile = '../../_data/tweets.json.cache'; // A cachefile will be placed in _data/
$json = @file_get_contents("http://search.twitter.com/search.json?result_type=recent&rpp=$show&q=%23" . $hashtag . "%20-RT");
if (!empty($json)) {
  $fp = fopen($cacheFile, 'w');
  fwrite($fp, $json);
  fclose($fp);
} else {
  echo "Could not get tweets";
  exit;
}
?>