Nazariy Nazariy - 3 months ago 23
PHP Question

How to insert HTML to PHP DOMNode?

Is there any way I can insert an HTML template to existing DOMNode without content being encoded?

I have tried to do that with:

$dom->createElement('div', '<h1>Hello world</h1>');
$dom->createTextNode('<h1>Hello world</h1>');


The output is pretty much the same, with only difference that first code would wrap it in a div.
I have tried to loadHTML from string but I have no idea how can I append it's body content to another DOMDocument.

In javascript, this process seems to be quite simple and obvious.

Answer

It works with another DOMDocument for parsing the HTML code. But you need to import the nodes into the main document before you can use them in it:

$newDiv = $dom->createElement('div');
$tmpDoc = new DOMDocument();
$tmpDoc->loadHTML($str);
foreach ($tmpDoc->getElementsByTagName('body')->item(0)->childNodes as $node) {
    $node = $dom->importNode($node);
    $newDiv->appendChild($node);
}

And as a handy function:

function appendHTML(DOMNode $parent, $source) {
    $tmpDoc = new DOMDocument();
    $tmpDoc->loadHTML($source);
    foreach ($tmpDoc->getElementsByTagName('body')->item(0)->childNodes as $node) {
        $node = $parent->ownerDocument->importNode($node);
        $parent->appendChild($node);
    }
}

Then you can simply do this:

$elem = $dom->createElement('div');
appendHTML($elem, '<h1>Hello world</h1>');