Nazariy Nazariy - 1 year ago 112
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 Source

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();
foreach ($tmpDoc->getElementsByTagName('body')->item(0)->childNodes as $node) {
    $node = $dom->importNode($node);

And as a handy function:

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

Then you can simply do this:

$elem = $dom->createElement('div');
appendHTML($elem, '<h1>Hello world</h1>');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download