Search code examples
phpdomdocument

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


I try to add some piece of HTML code which contains an attribute like {{ some_attr }} i.e. with empty value. For example:

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

Since appendXML() doesn't pass empty attribute, I don't receive my div with New content

I've tried

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

and

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

before saveHTML() as described by the link https://stackoverflow.com/a/39671548

I've also tried

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

as mentioned by the link https://stackoverflow.com/a/15998516

But none of the solutions work

Is it possible to append a code with empty attribute using appendXML() ?


Solution

  • Ok, I've just found a solution from 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);
        }
    }
    ...