DOM更改元素内容

时间:2011-08-12 09:22:07

标签: php dom domdocument

如何使用PHP DOM函数更改元素内容?

深入...我已经查询了我的元素,修改了属性,现在想要更改它的内容,我该怎么做?

1 个答案:

答案 0 :(得分:34)

如果要设置元素的文本内容,请设置nodeValue属性:

$el = $dom->getElementById('foo');
$el->nodeValue = 'hello world';

请注意,这会自动转义<>,因此您无法像这样插入HTML。为此,您必须执行DOMDocument::createDocumentFragment

之类的操作
$frag = $dom->createDocumentFragment();
$frag->appendXML('<h1>foo</h1>');
$el->appendChild($frag);