我还没有找到设置默认编码的方法(还),但在这种情况下恢复模式可能是可行的。
当 libxml 遇到编码错误并且没有明确设置编码时,它会从 unicode/utf8 切换到 latin1 并继续解析文档。但在解析器上下文中,该属性wellFormed
设置为 0/false。wellFormed
如果为真或DOMDocument 对象的属性为真,PHP 的 DOM 扩展认为文档有效recover
。
<?php
// german Umlaut ä in latin1 = 0xE4
$xml = '<foo>'.chr(0xE4).'</foo>';
$doc = new DOMDocument;
$b = $doc->loadxml($xml);
echo 'with doc->recover=false(default) : ', ($b) ? 'success':'failed', "\n";
$doc = new DOMDocument;
$doc->recover = true;
$b = $doc->loadxml($xml);
echo 'with doc->recover=true : ', ($b) ? 'success':'failed', "\n";
印刷
Warning: DOMDocument::loadXML(): Input is not proper UTF-8, indicate encoding !
Bytes: 0xE4 0x3C 0x2F 0x66 in Entity, line: 1 in test.php on line 6
with doc->recover=false(default) : failed
Warning: DOMDocument::loadXML(): Input is not proper UTF-8, indicate encoding !
Bytes: 0xE4 0x3C 0x2F 0x66 in Entity, line: 1 in test.php on line 11
with doc->recover=true : success
您仍然会收到警告消息(可以使用 @$doc->load() 抑制),并且它还会显示在内部 libxml 错误中(仅在解析器从 utf8 切换到 latin1 时出现一次)。此特定错误的错误代码将为 9 (XML_ERR_INVALID_CHAR)。
<?php
$xml = sprintf('<foo>
<ae>%s</ae>
<oe>%s</oe>
&
</foo>', chr(0xE4),chr(0xF6));
libxml_use_internal_errors(true);
$doc = new DOMDocument;
$doc->recover = true;
libxml_clear_errors();
$b = $doc->loadxml($xml);
$invalidCharFound = false;
foreach(libxml_get_errors() as $error) {
if ( 9==$error->code && !$invalidCharFound ) {
$invalidCharFound = true;
echo "found invalid char, possibly harmless\n";
}
else {
echo "hm, that's probably more severe: ", $error->message, "\n";
}
}