我正在尝试像这样设置元素的节点值:
$element->nodeValue = get_include_contents(DIR_APP . Config::getParam("layout_dir").$itemTemplateFilePath);
get_include_contents
函数返回如下所示的 html:
<li>Person <b>{{ $name }}</b> is <span>{{ $age }}</span> years old. <a href="" data-id="{{ $id }}" data-event="Event: 'onclick', Action: 'deleteThePerson'">X</a></li>
问题是<和>被<
和>
所取代。如何解决?如何设置包含其他 html 的元素的内部 html?和>
如果要将html
块添加到DOM
树中,则应使用appendChild
而不是nodeValue
方法。
问题是您首先需要创建一个 DON Node
.
这是有关如何执行此操作的技巧:
// This will be the original doc we work on.
$doc1 = new DOMDocument();
$doc1->loadHTML("<html><body><p></p></body></html>");
$element = $doc1->getElementsByTagName('p')[0];
// Here is the trick - we create a new document
$doc2 = new DOMDocument();
$s = '<li>Person <b>{{ $name }}</b> is <span>{{ $age }}</span> years old. <a href="" data-id="{{ $id }}" data-event="Event: 'onclick', Action: 'deleteThePerson'">X</a></li>';
// and load the html we need into that document
$doc2->loadHTML($s);
// Now we can append the node from `doc2` into `doc1`
$element->appendChild($doc1->importNode($doc2->getElementsByTagName('li')[0], true));
echo $doc1->saveHTML();
您需要记住的重要一点是,您必须使用
importNode
方法才能将该node
从doc2
移动到doc1
.只有在导入该节点后 - 才能使用appendChild
函数。
上面示例中的输出将是:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p><li>Person <b>{{ $name }}</b> is <span>{{ $age }}</span> years old. <a href="" data-id="{{ $id }}" data-event="Event: 'onclick', Action: 'deleteThePerson'">X</a></li></p></body></html>