使用DOMDocument解析布尔属性


Parse boolean attributes with DOMDocument

我试图解析一个简单的配置文件与最小化布尔属性和DOMDocument没有它。我正在尝试加载以下内容:

<config>
    <text id='name' required>
        <label>Name:</label>
    </text>
</config>

和下面的代码

$dom = new DOMDocument();
$dom->preserveWhiteSpace=FALSE;
if($dom->LoadXML($template) === FALSE){
    throw new Exception("Could not parse template");
}

我得到一个警告

Warning: DOMDocument::loadXML(): Specification mandate value for attribute required in Entity, line: 2

我是否缺少一个标志或一些东西来让DOMDocument解析最小布尔属性?

没有值的属性在XML 1.0或1.1中都不是有效的语法,所以您拥有的不是XML。你应该把它修好。

假装不可能,你可以使用:

$dom->loadHTML($template, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);

,它使用一种更宽容的解析模式,但是您会得到关于无效HTML标记的警告。因此,您还需要libxml_use_internal_errors(true)libxml_get_errors()(无论如何您都应该使用它们来处理错误),并忽略错误代码为801的任何内容。

例子:

$notxml = <<<'XML'
<config>
    <text id='name' required>
        <label>Name:</label>
    </text>
</config>
XML;
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($notxml, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);
foreach (libxml_get_errors() as $error) {
    // Ignore unknown tag errors
    if ($error->code === 801) continue;
    throw new Exception("Could not parse template");
}
libxml_clear_errors();
// do your stuff if everything didn't go completely awry
echo $dom->saveHTML(); // Just to prove it worked

输出:

<config>
    <text id="name" required>
        <label>Name:</label>
    </text>
</config>