微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 如何处理警告:SimpleXMLElement :: __ construct()?

我在本地主机运行时遇到此错误,如果互联网断开连接(如果互联网连接正常)我想处理此错误,“错误可以显示”但是想要在PHP页面上处理不致命的错误中断.

Warning: SimpleXMLElement::__construct() [simplexmlelement.--construct]:
  PHP_network_getaddresses: getaddrinfo Failed: No such host is kNown.
  in F:\xampp\htdocs\shoptpoint\sections\docType_head_index.PHP on line 30

但我正在尝试使用try-catch处理.以下是我的代码

$apiurl="http://publisher.usb.api.shopping.com/publisher/3.0/rest/GeneralSearch?apiKey=78b0db8a-0ee1-4939-a2f9-d3cd95ec0fcc&trackingId=7000610&categoryId='5855855'";

try{
  new SimpleXMLElement($apiurl,null, true);
}catch(Exception $e){
  echo $e->getMessage();
}

如何处理错误,我的页面可以执行项目结束?

解决方法:

使用set_error_handler,您可以执行以下操作将SimpleXMLElement引发的任何通知/警告转换为可捕获的异常.

请考虑以下事项: –

<?PHP
function getData() {
    return new SimpleXMLElement('http://10.0.1.1', null, true);
}

$xml = getData();

/*
    PHP Warning:  SimpleXMLElement::__construct(http://10.0.1.1): Failed to open stream: Operation timed out
    PHP Warning:  SimpleXMLElement::__construct(): I/O warning : Failed to load external entity "http://10.0.1.1"
    PHP Fatal error:  Uncaught exception 'Exception' with message 'String Could not be parsed as XML'
*/

看看我们如何在抛出SimpleXMLElement异常之前得到2个警告?好吧,我们可以将这些转换为这样的异常: –

<?PHP
function getData() {

    set_error_handler(function($errno, $errstr, $errfile, $errline) {
        throw new Exception($errstr, $errno);
    });

    try {
        $xml = new SimpleXMLElement('http://10.0.1.1', null, true);
    }catch(Exception $e) {
        restore_error_handler();
        throw $e;
    }

    return $xml;
}

$xml = getData();

/*
    PHP Fatal error:  Uncaught exception 'Exception' with message 'SimpleXMLElement::__construct(http://10.0.1.1): Failed to open stream: Operation timed out'
*/

祝好运,

安东尼.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。