Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append source html to a DOMElement in PHP?

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.

like image 204
fabio Avatar asked Jan 20 '11 19:01

fabio


3 Answers

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(); 
like image 97
Gordon Avatar answered Nov 18 '22 12:11

Gordon


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);
like image 33
Dan Lugg Avatar answered Nov 18 '22 11:11

Dan Lugg


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.

like image 2
lonesomeday Avatar answered Nov 18 '22 10:11

lonesomeday