我正在调用响应true
或false
的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;
试试这个,PHP有一个空()函数。
$content = file_get_contents($url);
if (empty($content)) {
echo "Unexpected error in response at: {$url}\n";
} else {
return json_decode($content);