How to append source html to a DOMElement in PHP?
Asked Answered
H

3

12

Is there a way of appending source html into a DOMElement? Something like this:

$trElement->appendSource("<a href='?select_user=4'>Username</a>");

It would parse that fragment and then append it.

Henninger answered 20/1, 2011 at 19:13 Comment(0)
A
17

You are looking for

- DOMDocumentFragment::appendXML — Append raw XML data

Example from Manual:

$doc = new DOMDocument();
$doc->loadXML("<root/>");
$f = $doc->createDocumentFragment();
$f->appendXML("<foo>text</foo><bar>text2</bar>");
$doc->documentElement->appendChild($f);
echo $doc->saveXML(); 
Accomplice answered 20/1, 2011 at 19:20 Comment(2)
Note: Your HTML input must also be valid XML otherwise you will get errors. The way I have done this is to create another document, load the HTML into that (as HTML, not XML) and then deep-import the newly created nodes back into my original document.Muscadine
In case you'll get output conversion failed due to conv error on DOMDocument::saveHTML() as result of adding external code, you need to force conversion to specific encoding standard e.g. via utf8_encode().Downturn
A
6

If you don't have a reference to the document root in scope, you can always access it via the ownerDocument property of an arbitrary node:

$frag = $trElement->ownerDocument->createDocumentFragment();
$frag->appendXML("<a href='?select_user=4'>Username</a>");
$trElement->appendChild($frag);
Awash answered 20/1, 2011 at 19:21 Comment(0)
I
3

Yes, you can do this with DOMDocument::createDocumentFragment:

$fragment = $dom->createDocumentFragment();
$fragment->appendXML('<a href="select_user=4">Username</a>');
$element->appendChild($fragment);

In this case, it would be simpler to do it with a normal createElement call:

$el = $dom->createElement('a', 'Username');
$el->setAttribute('href', 'select_user=4');
$element->appendChild($el);

In each case, $element is the DOM element to which you want to append your code.

Informed answered 20/1, 2011 at 19:22 Comment(1)
"In this case, it would be simpler to do it with a normal createElement call:", this is not my case since in my app I can have an arbitrary input so the fragment is ok for this.Henninger

© 2022 - 2024 — McMap. All rights reserved.