PHP Catching a SimpleXMLElement parse error [close

2019-02-17 11:29发布

I have a script that parses some XML (adf) stuff. Sometimes we receive broken XML data (ie- syntax, no ending tag, etc.).

SimpleXMLElement throws an error and kills my script, how could assign something like $xml_body = new SimpleXMLElement ($adf_xml); and catch the parse exception?


Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /home//Work//script/email_leads.php:46
Stack trace:
0 /home//Work//script/email_leads.php(46): SimpleXMLElement->__construct('<?xml version="...')
1 /home//Work//script/email_leads.php(97): generateFeed()
2 {main}

3条回答
一夜七次
2楼-- · 2019-02-17 11:43

xml_parse returns a boolean value indicating whether the XML has been parsed successfully. Therefore, this should work:

$fp = fopen($xml_file, "r");
$xml_data = fread($fp, 80000);

if(!(xml_parse($xml_parser, $xml_data, feof($fp)))){
    # do something
} 
查看更多
一夜七次
3楼-- · 2019-02-17 11:46
libxml_use_internal_errors(true);
查看更多
Luminary・发光体
4楼-- · 2019-02-17 12:04

Ok, so apparently catching XML Parse errors is somewhat of a Holy Grail... I ended up just

try { $x = new SimpleXMLElement($y); } catch (Exception $e) { echo $e; }
查看更多
登录 后发表回答