使用DOMDocument解析布尔属性 [英] Parse boolean attributes with DOMDocument

查看:69
本文介绍了使用DOMDocument解析布尔属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to parse a simple config file with minimized Boolean attributes and the DOMDocument is not having it. I am trying to load the following:

<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来解析最小布尔属性的内容?

Am I missing a flag or something to get DOMDocument to parse the minimum boolean attribute?

推荐答案

没有值的属性在 XML 1.0 1.1 ,因此您拥有不是XML。

An attribute without a value is not valid syntax in either XML 1.0 or 1.1, so what you have isn't XML. You should get that fixed.

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

Pretending that's not possible, you can use:

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

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

instead, which uses a parsing mode that's much more forgiving, but you'll get warnings about invalid HTML tags. So you'll also need libxml_use_internal_errors(true) and libxml_get_errors() (which you should probably be using anyway to deal with errors) and ignore anything with an error code of 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



输出:



Outputs:

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

这篇关于使用DOMDocument解析布尔属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆