如何将HTML插入PHP DOMNode? [英] How to insert HTML to PHP DOMNode?
问题描述
我有没有办法将HTML模板插入到现有的DOMNode中,而不需要编码?
Is there any way I can insert an HTML template to existing DOMNode without content being encoded?
$ b
I have tried to do that with:
$dom->createElement('div', '<h1>Hello world</h1>');
$dom->createTextNode('<h1>Hello world</h1>');
输出几乎相同,只不过第一个代码将它包装在一个div中。
我尝试从字符串加载HTML,但我不知道如何将其身体内容附加到另一个DOMDocument。
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.
在javascript中,这个过程似乎是
In javascript, this process seems to be quite simple and obvious.
推荐答案
它与另一个DOMDocument一起用于解析HTML代码。但是,您需要导入节点到主文档中,然后才能使用它们:
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();
$tmpDoc->loadHTML($str);
foreach ($tmpDoc->getElementsByTagName('body')->item(0)->childNodes as $node) {
$node = $dom->importNode($node);
$newDiv->appendChild($node);
}
作为一个方便的功能:
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);
$parent->appendChild($node);
}
}
然后你可以这样做:
$elem = $dom->createElement('div');
appendHTML($elem, '<h1>Hello world</h1>');
这篇关于如何将HTML插入PHP DOMNode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!