How to append source html to a DOMElement in PHP?

被刻印的时光 ゝ 提交于 2019-11-28 11:10:13

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!