Handle XML Errors with PHP’s SimpleXMLElement

I don’t write procedural code any longer, so when I use PHP’s simple xml package, I use the object-oriented approach. Here’s how to handle, or suppress error/exceptions, when creating a SimpleXMLElement object.

libxml_use_internal_errors(TRUE); // this turns off spitting errors on your screen
try {
  $xml = new SimpleXMLElement($xmlStringOfData);
} catch (Exception $e) {
  // Do something with the exception, or ignore it.
}

That procedural call to libxml_use_internal_errors(TRUE) is necessary if you want to suppress the errors from displaying on your screen or STDOUT.

Share Button