在DOMDocument中设置nodeValue内容html


Set nodeValue content html in DOMDocument

我用dom对象创建了新元素:

$doc = new 'DOMDocument();
$link = $doc->createElement('a'); 
$link->setAttribute('href', '/#');
$link.nodeValue = '<b>Text</b>';
$html = $this->doc->saveHTML();

此变量"$html"包含内容:

<a href="/#">&lt;b&gt;Text&lt;/b&gt;</a>

我想输出:

<a href="/#"><b>Text</b></a>

如何正确设置"nodeValue"?这样做可能吗?

非常感谢。

通过使用DOMDocumentFragment及其appendXML()方法

<?php
$doc = new 'DOMDocument();
$link = $doc->appendChild($doc->createElement('html'))
    ->appendChild( $doc->createElement('body') )
    ->appendChild( $doc->createElement('a') );
$link->setAttribute('href', '/#');

$fragment = $doc->createDocumentFragment();
$fragment->appendXML('<b>text</b>');
$link->appendChild($fragment);

echo $doc->saveHTML();

打印

<html><body><a href="/#"><b>text</b></a></body></html>