libxml errors are mainly generated when reading or writing an xml document, as it automatically checks.
So, here is where you should focus, and you don't need to overwrite set_error_handler . Here is the proof of concept
Use internal errors
libxml_use_internal_errors ( true );
XML example
$xmlstr = <<< XML <?xml version='1.0' standalone='yes'?> <movies> <movie> <titles>PHP: Behind the Parser</title> </movie> </movies> XML; echo "<pre>" ;
I think this is an example of what you want to achieve.
try { $loader = new XmlLoader ( $xmlstr ); } catch ( XmlException $e ) { echo $e->getMessage(); }
XMLLoader Class
class XmlLoader { private $xml; private $doc; function __construct($xmlstr) { $doc = simplexml_load_string ( $xmlstr ); if (! $doc) { throw new XmlException ( libxml_get_errors () ); } } }
Class xmlexception
class XmlException extends Exception { private $errorMessage = ""; function __construct(Array $errors) { $x = 0; foreach ( $errors as $error ) { if ($error instanceof LibXMLError) { $this->parseError ( $error ); $x ++; } } if ($x > 0) { parent::__construct ( $this->errorMessage ); } else { parent::__construct ( "Unknown Error XmlException" ); } } function parseError(LibXMLError $error) { switch ($error->level) { case LIBXML_ERR_WARNING : $this->errorMessage .= "Warning $error->code: "; break; case LIBXML_ERR_ERROR : $this->errorMessage .= "Error $error->code: "; break; case LIBXML_ERR_FATAL : $this->errorMessage .= "Fatal Error $error->code: "; break; } $this->errorMessage .= trim ( $error->message ) . "\n Line: $error->line" . "\n Column: $error->column"; if ($error->file) { $this->errorMessage .= "\n File: $error->file"; } } }
Output example
Fatal Error 76: Opening and ending tag mismatch: titles line 4 and title Line: 4 Column: 46
I hope this helps
thanks
source share