如何在 PHP DOMDocument 中用空属性附加 XML(fragment)



我尝试添加一些HTML代码,其中包含一个属性,例如{{ some_attr }},即具有空值。例如:

<?php
$pageHTML = '<!doctype html>
<html>
<head>
</head>
<body>
<div id="root">Initial content</div>
</body>
</html>';
$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($pageHTML);
libxml_use_internal_errors(false);
$tmplCode = '<div {{ some_attr }}>New content</div>';
foreach($dom->getElementsByTagName('body')[0]->getElementsByTagName('*') as $node) {
    if($node->getAttribute('id') == 'root') {
        $fragment = $dom->createDocumentFragment();
        $fragment->appendXML($tmplCode);
        $node->appendChild($fragment);
    }
}
echo $dom->saveHTML((new DOMXPath($dom))->query('/')->item(0));
?>

由于appendXML()不传递空属性,因此我不会收到带有New content的div

我试过了

$dom->loadHTML($pageHTML, 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();

saveHTML()之前,如链接中所述 https://stackoverflow.com/a/39671548

我也试过

@@$fragment = $dom->createDocumentFragment();
@@$fragment->appendXML($tmplCode);

如链接所述 https://stackoverflow.com/a/15998516

但是没有一个解决方案有效

是否可以使用 appendXML() 附加具有空属性的代码?

好的,我刚刚从 https://stackoverflow.com/a/4401089/3208225 中找到了一个解决方案

...
if($node->getAttribute('id') == 'root') {
    $tmpDoc = new DOMDocument();
    $tmpDoc->loadHTML($tmplCode);
    foreach ($tmpDoc->getElementsByTagName('body')->item(0)->childNodes as $newNode) {
        $newNode = $dom->importNode($newNode, true);
        $node->nodeValue = '';
        $node->appendChild($newNode);
    }
}
...

最新更新