PHP libxml_get_errors() Function
The PHP libxml_get_errors() function gets the errors from the libxml error buffer.
Syntax
libxml_get_errors()
Parameters
No parameter is required.
Return Value
Returns an array with LibXMLError objects if there are any errors in the buffer, or an empty array otherwise.
Example: libxml_get_errors() example
The example below shows the usage of libxml_get_errors() function.
<?php libxml_use_internal_errors(true); //contains mismatched tags $xmlstr = <<<XML <mail> <To>John Smith</too> <From>Marry G.</From> <Subject>Happy Birthday</Subject> <body>Happy birthday. Live your life with smiles.</Body> </mail> XML; $doc = simplexml_load_string($xmlstr); $xml = explode("\n", $xmlstr); if ($doc === false) { $errors = libxml_get_errors(); //displaying errors occurred print_r($errors); //clearing the libxml error buffer libxml_clear_errors(); } ?>
The output of the above code will be:
Array ( [0] => LibXMLError Object ( [level] => 3 [code] => 76 [column] => 23 [message] => Opening and ending tag mismatch: To line 2 and too [file] => [line] => 2 ) [1] => LibXMLError Object ( [level] => 3 [code] => 76 [column] => 59 [message] => Opening and ending tag mismatch: body line 2 and Body [file] => [line] => 5 ) )
Example: building a simple error handler
The example below shows how to build a simple libxml error handler.
<?php libxml_use_internal_errors(true); //contains mismatched tags $xmlstr = <<<XML <mail> <To>John Smith</too> <From>Marry G.</From> <Subject>Happy Birthday</Subject> <body>Happy birthday. Live your life with smiles.</Body> </mail> XML; $doc = simplexml_load_string($xmlstr); $xml = explode("\n", $xmlstr); if ($doc === false) { $errors = libxml_get_errors(); //displaying errors occurred foreach ($errors as $error) { echo display_xml_error($error, $xml)."\n"; } //clearing the libxml error buffer libxml_clear_errors(); } //function to display error message function display_xml_error($error, $xml) { $message = ""; switch ($error->level) { case LIBXML_ERR_WARNING: $message .= "Warning $error->code: "; break; case LIBXML_ERR_ERROR: $message .= "Error $error->code: "; break; case LIBXML_ERR_FATAL: $message .= "Fatal Error $error->code: "; break; } $message .= trim($error->message) . "\n Line: $error->line" . "\n Column: $error->column"; if ($error->file) { $message .= "\n File: $error->file"; } return $message; } ?>
The output of the above code will be:
Fatal Error 76: Opening and ending tag mismatch: To line 2 and too Line: 2 Column: 23 Fatal Error 76: Opening and ending tag mismatch: body line 2 and Body Line: 5 Column: 59
❮ PHP Libxml Reference