4

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

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?

4

2 回答 2

6

使用 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'
*/

祝你好运,

安东尼。

于 2013-06-09T17:25:53.520 回答
0

如果出于某种原因您不想设置错误处理程序,您还可以使用一些 libxml 函数来抑制E_WARNING引发:


// remembers the old setting and enables usage of libxml internal error handler
$previousSetting = libxml_use_internal_errors(true);

// still need to try/catch because invalid XML raises an Exception
try {
    // XML is missing root node
    new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>',null, true);
} catch(Exception $e) {
    echo $e->getMessage(); // this won't help much: String could not be parsed as XML
    $xmlError = libxml_get_last_error(); // returns object of class LibXMLError or FALSE
    if ($xmlError) {
        echo $xmlError->message; // this is more helpful: Start tag expected, '<' not found
    }
}

// sets libxml usage of internal error handler to previous setting
libxml_use_internal_errors($previousSetting);

或者,您可以使用libxml_get_errors()而不是libxml_get_last_error()获取所有错误。有了它,您可以获得关于将 XML 解析为LibXMLError对象数组的所有错误。

一些有用的链接:

于 2019-05-22T13:36:16.970 回答