PHP simplexml_load_file捕获403 [英] PHP simplexml_load_file catch 403
问题描述
我正在使用以下PHP:
I am using the following PHP:
$xml = simplexml_load_file($request_url) or die("url not loading");
我使用:
$status = $xml->Response->Status->code;
检查响应状态. 200一切正常,继续.
To check the status of the response. 200 bening everything is ok, carry on.
但是,如果出现403访问被拒绝的错误,如何在PHP中捕获此错误,以便返回用户友好的警告?
However if I get a 403 access denied error, how do I catch this in PHP so I can return a user friendly warning?
推荐答案
要从对simplexml_load_file()
的调用中检索HTTP响应代码,我知道的唯一方法是使用鲜为人知的PHP $http_response_header
.每次通过HTTP包装器发出HTTP请求时,都会自动将该变量自动创建为包含每个响应标头的数组.换句话说,每次您使用simplexml_load_file()
或file_get_contents()
以及以"http://"开头的URL
To retrieve the HTTP response code from a call to simplexml_load_file()
, the only way I know is to use PHP's little known $http_response_header
. This variable is automagically created as an array containing each response header separately, everytime you make a HTTP request through the HTTP wrapper. In other words, everytime you use simplexml_load_file()
or file_get_contents()
with a URL that starts with "http://"
您可以使用print_r()
检查其内容,例如
You can inspect its content with a print_r()
such as
$xml = @simplexml_load_file($request_url);
print_r($http_response_header);
但是,在您的情况下,您可能想使用 file_get_contents()
然后,测试您是否收到了4xx响应,如果没有,则将正文传递给simplexml_load_string()
.例如:
In your case, though, you might want to retrieve the XML separately with file_get_contents()
then, test whether you got a 4xx response, then if not, pass the body to simplexml_load_string()
. For instance:
$response = @file_get_contents($request_url);
if (preg_match('#^HTTP/... 4..#', $http_response_header[0]))
{
// received a 4xx response
}
$xml = simplexml_load_string($response);
这篇关于PHP simplexml_load_file捕获403的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!