如何将 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?
我尝试这样做:
$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, true);
$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, true);
$parent->appendChild($node);
}
}
然后你可以简单地这样做:
Then you can simply do this:
$elem = $dom->createElement('div');
appendHTML($elem, '<h1>Hello world</h1>');
这篇关于如何将 HTML 插入到 PHP DOMNode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!