我正在使用以下PHP:

$xml = simplexml_load_file($request_url) or die("url not loading");

我用:

$status = $xml->Response->Status->code;

检查响应的状态。 200 BENing一切正常,继续。

但是,如果我获得403访问被拒绝的错误,我该如何在PHP中捕获此错误,以便我可以返回用户友好的警告?

有帮助吗?

解决方案

从调用到 simplexml_load_file(), ,我知道的唯一方法是使用PHP鲜为人知的 $http_response_header. 。该变量是自动创建的,作为一个数组,每次通过HTTP包装器制作HTTP请求时,分别包含每个响应标头。换句话说,每次使用 simplexml_load_file() 或者 file_get_contents() 以“ http://”开头的URL

您可以使用 print_r()

$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);

其他提示

您必须使用类似的东西 卷曲模块 或者 HTTP模块 要获取文件,然后使用他们提供的功能来检测HTTP错误,然后将字符串从它们传递到 Simplexml_load_string.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top