PHP simplexml_load_file捕获403

Sco*_*ler 1 php xml simplexml http-status-code-403

我使用以下PHP:

$xml = simplexml_load_file($request_url) or die("url not loading");
Run Code Online (Sandbox Code Playgroud)

我用:

$status = $xml->Response->Status->code;
Run Code Online (Sandbox Code Playgroud)

检查响应的状态.200 bening一切都好,继续.

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

Jos*_*vis 8

要从调用中检索HTTP响应代码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);
Run Code Online (Sandbox Code Playgroud)

但是,在您的情况下,您可能希望单独检索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);
Run Code Online (Sandbox Code Playgroud)