我如何处理警告:SimpleXMLElement::__construct()? [英] How do I handle Warning: SimpleXMLElement::__construct()?
问题描述
我在本地主机上运行时遇到此错误,如果 Internet 断开连接(如果 Internet 连接正常)我想处理此错误,错误可以显示"但想处理 PHP 上的非致命错误中断页面.
I'm getting this error when I run in local host, if internet is disconnected (if internet is connect its ok) I want to handle this error, "error can show " but want to handle not fatal error break on PHP page.
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 进行处理.下面是我的代码
but I'm trying to handle using try-catch. Below is my code
$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();
}
我如何处理错误并且我的页面可以在项目结束时执行?
How do I handle the error and my page can execute end of the project?
推荐答案
使用 set_error_handler,您可以执行以下操作,将 SimpleXMLElement 引发的任何通知/警告转换为可捕获的异常.
Using set_error_handler, you can do the following to convert any notices/warnings raised by SimpleXMLElement into a catchable Exception.
采取以下措施:-
<?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 个警告了吗?好吧,我们可以像这样将它们转换为异常:-
See how we get 2 Warnings before the the Exception from SimpleXMLElement is thrown? Well, we can convert those to an Exception like this:-
<?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'
*/
祝你好运,
安东尼.
这篇关于我如何处理警告:SimpleXMLElement::__construct()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!