我正在使用以下 PHP:
$xml = simplexml_load_file($request_url) or die("url not loading");
I use:
$status = $xml->Response->Status->code;
检查响应的状态。 200 一切都好,继续。
但是,如果我收到 403 访问被拒绝错误,我如何在 PHP 中捕获此错误,以便返回用户友好的警告?
从调用中检索 HTTP 响应代码simplexml_load_file()
,我知道的唯一方法就是使用PHP鲜为人知的$http_response_header
。每次您通过 HTTP 包装器发出 HTTP 请求时,此变量都会自动创建为一个数组,其中单独包含每个响应标头。换句话说,每次你使用simplexml_load_file()
or file_get_contents()
包含以“http://”开头的 URL
您可以使用以下命令检查其内容print_r()
such as
$xml = @simplexml_load_file($request_url);
print_r($http_response_header);
不过,就您的情况而言,您可能希望使用以下命令单独检索 XML:file_get_contents()然后,测试您是否收到 4xx 响应,如果没有,则将正文传递给simplexml_load_string()
。例如:
$response = @file_get_contents($request_url);
if (preg_match('#^HTTP/... 4..#', $http_response_header[0]))
{
// received a 4xx response
}
$xml = simplexml_load_string($response);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)