如何在 PHP DOMDocument 中附加具有空属性的 XML(片段)

How to appendXML(fragment) with empty attribute in PHP DOMDocument

我尝试添加一些 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() 之前 link

我也试过了

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

如link所述

但是 none 的解决方案有效

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

好的,我刚刚从

找到了解决方案
...
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);
    }
}
...