libxml_get_errors()
(PHP 5 >= 5.1.0, PHP 7)
Retrieve array of errors
说明
libxml_get_errors(void): array
Retrieve array of errors.
返回值
Returns an array with LibXMLError objects if there are any errors in the buffer, or an empty array otherwise.
范例
Example #1 A libxml_get_errors() example
This example demonstrates how to build a simple libxml error handler.
<?php libxml_use_internal_errors(true); $xmlstr = <<< XML <?xml version='1.0' standalone='yes'?> <movies> <movie> <titles>PHP: Behind the Parser</title> </movie> </movies> XML; $doc = simplexml_load_string($xmlstr); $xml = explode("\n", $xmlstr); if ($doc === false) { $errors = libxml_get_errors(); foreach ($errors as $error) { echo display_xml_error($error, $xml); } libxml_clear_errors(); } function display_xml_error($error, $xml) { $return = $xml[$error->line - 1] . "\n"; $return .= str_repeat('-', $error->column) . "^\n"; switch ($error->level) { case LIBXML_ERR_WARNING: $return .= "Warning $error->code: "; break; case LIBXML_ERR_ERROR: $return .= "Error $error->code: "; break; case LIBXML_ERR_FATAL: $return .= "Fatal Error $error->code: "; break; } $return .= trim($error->message) . "\n Line: $error->line" . "\n Column: $error->column"; if ($error->file) { $return .= "\n File: $error->file"; } return "$return\n\n--------------------------------------------\n\n"; } ?>
以上例程会输出:
<titles>PHP: Behind the Parser</title> ----------------------------------------------^ Fatal Error 76: Opening and ending tag mismatch: titles line 4 and title Line: 4 Column: 46 --------------------------------------------
参见
libxml_get_last_error()
Retrieve last error from libxmllibxml_clear_errors()
Clear libxml error buffer
Please beware that the column property seems almost always to be invalid. I thought it only occurred when the line in question was long (and I was just about to submit a bug report with an example), however, at the time of posting, you can even see the problem in the example provided on this page: line 4 does not even have 46 characters. Where the XML line is long, the difference can be very large. This property comes from the libxml extension, so in any case I don't think this is a PHP bug, however it is worth knowing that the value might be totally unreliable to save some confusion. The PHP documentation page for the libXMLError class gives some indication, stating: "This property isn't entirely implemented in libxml and therefore 0 is often returned." (My libxml version: 2.9.1)