如何使用PHP自定义错误消息如果可以';t连接到web服务(JSON)


how to custom error msg with PHP if can't connect to web service (JSON)

我正在使用PHP和JSON连接到一个Web服务。连接很好,但当(1)与webservice的连接丢失时,以及(2)如果webservice返回http500错误时,我想添加2条错误消息。

有什么办法吗??我是json的新手,所以不知道该怎么做。。。

这就是我连接并从网络服务获取数据的方式

$url = "http://webservice.com/{$account}?loc={$loc}"; 
$content = file_get_contents($url);
$json = json_decode($content, true);

对于错误1:

如果file_get_contents尝试加载的内容失败,则它将返回FALSE

对于错误2:

根据HTTP错误500在页面上的输出,您可以简单地使用file_get_contents,并使用strpos查找指示错误的特定字符串,然后采取相应的行动。

参考:http://php.net/manual/en/function.strpos.php