此示例演示如何构建简单的 libxml 错误处理程序。
<?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 .= "警告 $error->code: ";
break;
case LIBXML_ERR_ERROR:
$return .= "错误 $error->code: ";
break;
case LIBXML_ERR_FATAL:
$return .= "致命错误 $error->code: ";
break;
}
$return .= trim($error->message) .
"\n 行: $error->line" .
"\n 列: $error->column";
if ($error->file) {
$return .= "\n 文件: $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
--------------------------------------------