【问题标题】:PHP simplexml_load_file catch 403PHP simplexml_load_file 捕获 403
【发布时间】:2010-01-21 01:06:25
【问题描述】:

我正在使用以下 PHP:

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

我用:

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

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

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

【问题讨论】:

    标签: php xml simplexml http-status-code-403


    【解决方案1】:

    要从对simplexml_load_file() 的调用中检索HTTP 响应代码,我知道的唯一方法是使用PHP 鲜为人知的$http_response_header。每次您通过 HTTP 包装器发出 HTTP 请求时,此变量都会自动创建为一个单独包含每个响应标头的数组。换句话说,每次使用simplexml_load_file()file_get_contents() 时,URL 都以“http://”开头

    您可以使用print_r() 来检查其内容,例如

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

    但是,在您的情况下,您可能希望使用 file_get_contents() 单独检索 XML,然后测试您是否收到 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);
    

    【讨论】:

    • 我应该更清楚一点——尽管这样可以让我捕捉到错误并阻止脚本尝试做更多的事情。我仍然收到默认警告消息:Warning: file_get_contents(domain.com) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden 捕获它们的原因是我正在发出多个请求,并且希望在错误发生时干净地捕获错误并给出用户友好的警告而不是默认警告。
    • 然后您使用静音运算符@,如更新的 sn-p 中所示。 docs.php.net/manual/en/language.operators.errorcontrol.php
    【解决方案2】:

    您必须使用 the cURL modulethe HTTP module 之类的东西来获取文件,然后使用它们提供的功能来检测 HTTP 错误,然后将字符串从它们传递到 simplexml_load_string

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-29
      • 1970-01-01
      • 2013-06-03
      • 2015-05-31
      • 1970-01-01
      • 2011-06-21
      • 2018-02-11
      • 2016-10-16
      相关资源
      最近更新 更多