9

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}

hakre
  • 193,403
  • 52
  • 435
  • 836
Weston Watson
  • 5,344
  • 6
  • 24
  • 25
  • Uhm, are you sure that using SimpleXML here is what you want? If you expect non-wellformed data you shouldn't use draconian xml certainly, but use some DOM parser instead. – NikiC Nov 09 '10 at 19:35
  • this is a chron'd script that gets input from an INBOX (imap)... – Weston Watson Nov 09 '10 at 20:16
  • possible duplicate of [php: catch exception and continue execution, is it possible?](http://stackoverflow.com/questions/2132759/php-catch-exception-and-continue-execution-is-it-possible) – hakre Mar 05 '13 at 10:43

3 Answers3

12

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

Weston Watson
  • 5,344
  • 6
  • 24
  • 25
  • 6
    try / catch doesn't seem to work with SimpleXMLElement. Or at least it didn't for loading a non-xml file for me. – Jake May 14 '14 at 19:36
  • 6
    I found this did not work for me too. I had to use: $x = new \SimpleXMLElement($xmlString, LIBXML_NOERROR); This seem to give me a catchable Exception. For reference see PHP manual for [LIBXML_NOERROR](http://php.net/manual/en/libxml.constants.php) – PanPipes Sep 08 '15 at 16:05
  • @PanPipes works for App Engine Standard Environment – J261 Jun 07 '19 at 04:32
7
libxml_use_internal_errors(true);
hakre
  • 193,403
  • 52
  • 435
  • 836
bcosca
  • 17,371
  • 5
  • 40
  • 51
  • libxml_use_internal_errors does clear up the error logs a bit, my script is still going to die when it throws the Parse error... Thanks for the help/tip tho :) – Weston Watson Nov 09 '10 at 19:54
  • I once up vote for the top voted answer, however, I think it is better to supress the error by the function mentioned here. And you use libxml_get_errors or libxml_get_last_error to find out what's going on. – cwhsu Apr 17 '15 at 02:16
0

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
} 
Joel
  • 724
  • 5
  • 12