提问者:小点点

当响应可能为false时如何处理file_get_contents


我正在调用响应truefalse的url。 我想使用file_get_contents,但我不知道如何处理服务器错误。

$content = file_get_contents($url);
if ($content === false) {
  echo "Unexpected error in response at: {$url}\n";
  return false;
 } else {
     return json_decode($content);

$content的检查是必要的,因为服务器可以响应500并且file_get_contents在本例中返回false。 但false是有效的响应。 所以我在问,在这种情况下,有没有更好的模式可以使用。 谢啦!

UPDATE(with fix):过了一段时间,我发现我应该只返回$content,而不是解码后的内容。 那我以后还要处理解码。

$content = file_get_contents($url);
if ($content === false) {
  echo "Unexpected error in response at: {$url}\n";
 }
 return $content;

共1个答案

匿名用户

试试这个,PHP有一个空()函数。

$content = file_get_contents($url);
if (empty($content)) {
  echo "Unexpected error in response at: {$url}\n";
 } else {
     return json_decode($content);