Parse boolean attributes with DOMDocument

淺唱寂寞╮ 提交于 2019-12-25 07:59:11

问题


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>

with the following code

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

I am getting a warning that

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

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


回答1:


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);

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.

Example:

$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>


来源:https://stackoverflow.com/questions/39671357/parse-boolean-attributes-with-domdocument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!