Content with Style

Web Technique

DOMDocument loadXML throws errors: A bug?

by Pascal Opitz on April 22 2009, 17:37

So I was wondering why loadXML gives me parsing errors, despite a big try and catch around it ... it's not a bug they say.

Gavin Sinai put up a code snippet in the PHP.net reference, which shows how to set the error handler to get rid of it:


<?php
function HandleXmlError($errno, $errstr, $errfile, $errline)
{
   if ($errno==E_WARNING && (substr_count($errstr,"DOMDocument::loadXML()")>0))
   {
       throw new DOMException($errstr);
   }
   else
       return false;
}

function XmlLoader($strXml)
{
   set_error_handler('HandleXmlError');
   $dom = new DOMDocument();
   $dom->loadXml($strXml);
   restore_error_handler();
   return $dom;
 }

?>

Comments

  • You can also use "libxml_use_internal_errors" function and also have access to next functions:

    • libxml_clear_errors() - Clear libxml error buffer
    • libxml_get_errors() - Retrieve array of errors

    http://www.php.net/libxml_use_internal_errors

    
       libxml_use_internal_errors(true);
       $dom = new DOMDocument();
       $dom->loadXml($strXml);
       libxml_use_internal_errors(true);
    
    if($errors = libxml_get_errors()){ // do something }

    by Andreja Simovic on April 29 2009, 22:25 #

  • I remember posting this several years ago - glad I could be of assistance :)

    by Gavin Sinai on October 5 2009, 13:54 #