PHP libxml_get_errors() 函数从 libxml 错误缓冲区获取错误。
语法
libxml_get_errors()
参数
不需要参数。
返回值
返回一个数组,其中LibXMLError 对象(如果缓冲区中有任何错误),否则为空数组。
示例:libxml_get_errors() 示例
下面的示例显示了libxml_get_errors()函数的用法。
<?php
libxml_use_internal_errors(true);
//包含不匹配的标签
$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();
//显示发生错误
print_r($errors);
//清除libxml错误缓冲区
libxml_clear_errors();
}
?>
上述代码的输出将是:
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
)
)
示例:构建一个简单的错误处理程序
下面的示例展示了如何构建一个简单的 libxml 错误处理程序。
<?php
libxml_use_internal_errors(true);
//包含不匹配的标签
$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();
//显示发生错误
foreach ($errors as $error) {
echo display_xml_error($error, $xml)."\n";
}
//清除libxml错误缓冲区
libxml_clear_errors();
}
//显示错误信息的函数
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;
}
?>
上述代码的输出将是:
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