0

我正在编写一个应用程序,它使用 .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:如何处理代码中的错误?

4

1 回答 1

2

简单来说,使用 '@' 前缀作为函数。它禁止显示错误。在这里阅读更多

<?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;
}
?>
于 2013-04-11T11:56:08.137 回答