PHP Catching a SimpleXMLElement parse error

Weston Watson picture Weston Watson · Nov 9, 2010 · Viewed 15.8k times · Source

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}

Answer

Weston Watson picture Weston Watson · Nov 10, 2010

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

try { $x = new SimpleXMLElement($y, LIBXML_NOERROR); } catch (Exception $e) { echo $e; }

EDIT: thanks to @PanPipes