php domnode 赋值,如何将HTML插入到PHP DOMNode?

闻人望
2023-12-01

它与另一个DOMDocument一起用于parsingHTML代码。 但是您需要将节点导入主文档,然后才能在其中使用它们:

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

作为一个方便的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, true); $parent->appendChild($node); } }

那么你可以简单地做到这一点:

$elem = $dom->createElement('div'); appendHTML($elem, '

Hello world

');

您可以使用

DOMDocumentFragment::appendXML – 追加原始XML数据

例:

// just some setup $dom = new DOMDocument; $dom->loadXml('

'); $body = $dom->documentElement->firstChild; // this is the part you are looking for $template = $dom->createDocumentFragment(); $template->appendXML('
 类似资料: