PHP simplexml_load_file 捕获 403

发布于 2024-08-18 13:34:39 字数 289 浏览 4 评论 0原文

我正在使用以下 PHP:

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

我使用:

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

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

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

I am using the following PHP:

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

I use:

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

To check the status of the response. 200 bening everything is ok, carry on.

However if I get a 403 access denied error, how do I catch this in PHP so I can return a user friendly warning?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

紙鸢 2024-08-25 13:34:39

要从对 simplexml_load_file() 的调用中检索 HTTP 响应代码,我知道的唯一方法是使用 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);

,在您的情况下,您可能希望使用 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);

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://"

You can inspect its content with a print_r() such as

$xml = @simplexml_load_file($request_url);
print_r($http_response_header);

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);
一抹淡然 2024-08-25 13:34:39

您必须使用类似 cURL 模块HTTP模块来获取文件,然后使用它们提供的功能来检测 HTTP 错误,然后将字符串传递到 simplexml_load_string< /a>.

You'll have to use something like the cURL module or the HTTP module to fetch the file, then use the functionality provided by them to detect an HTTP error, then pass the string from them into simplexml_load_string.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文