PHP故障保护如果无法get_contents

时间:2014-07-09 16:41:31

标签: php json api

$file = "https://www.some-api.com/?a=get_info";

$doge = (object) json_decode(file_get_contents($file));

if ($doge == false){
echo "failure";
}

else
{
[my code]
};

我的脚本每隔一段时间就会失败,而不是一直只是间歇性地失败。 PHP错误表示它在获取文件内容时失败。

我在这里尝试使用其他语句(没有用),是在收到内容时显示不同的内容。我是否有一种简单的方法来添加故障保护,以便重新加载脚本或者如果api无法正确响应则运行不同的进程?

2 个答案:

答案 0 :(得分:1)

这条线永远不会是真的......

if ($doge == false){

鉴于$doge永远不会是假的:

$doge = (object) json_decode(file_get_contents($file));

始终$doge投射到某个对象。你不能这样做,仍然检查它是否是假的。您需要在演员表之前执行测试,因为......

  • 如果file_get_contents失败,则返回false
  • json_decode(false)返回NULL
  • (object) NULL返回stdClass类型的对象。

因此 - $doge永远不可能false

尝试在盲目json_decoding结果之前检查失败。然后,你甚至不需要(object)演员。

$data = file_get_contents($file);

if (data) {
  $doge = json_decode($data);
  [my code]
} else {
  echo "failure";
}

答案 1 :(得分:0)

json_decode() documentation中,它表示FALSE代表虚假值。如果找不到要翻译的值,则返回NULL。所以要小心if ...

故障安全将由

$doge = json_decode(file_get_contents($file));

if (!is_null($doge)){
  [decoded OK, your code here]
}
else
{
   [failsafe code here]
};