Php 如何使用DOMDocument替换节点的文本

Php 如何使用DOMDocument替换节点的文本,php,xml,rss,domdocument,nodes,Php,Xml,Rss,Domdocument,Nodes,这是我将现有XML文件或字符串加载到DOMDocument对象中的代码: $doc = new DOMDocument(); $doc->formatOutput = true; // the content actually comes from an external file $doc->loadXML('<rss version="2.0"> <channel> <title></title> <desc

这是我将现有XML文件或字符串加载到DOMDocument对象中的代码:

$doc = new DOMDocument();
$doc->formatOutput = true;

// the content actually comes from an external file
$doc->loadXML('<rss version="2.0">
<channel>
    <title></title>
    <description></description>
    <link></link>
</channel>
</rss>');

$doc->getElementsByTagName("title")->item(0)->appendChild($doc->createTextNode($titleText));
$doc->getElementsByTagName("description")->item(0)->appendChild($doc->createTextNode($descriptionText));
$doc->getElementsByTagName("link")->item(0)->appendChild($doc->createTextNode($linkText));
$doc=newDOMDocument();
$doc->formatOutput=true;
//内容实际上来自外部文件
$doc->loadXML($doc)
');
$doc->getElementsByTagName(“title”)->item(0)->appendChild($doc->createTextNode($titleText));
$doc->getElementsByTagName(“说明”)->item(0)->appendChild($doc->createTextNode($descriptionText));
$doc->getElementsByTagName(“link”)->item(0)->appendChild($doc->createTextNode($linkText));
我需要覆盖标题、说明和链接标记中的值。上面代码中的最后三行是我的尝试;但是,如果节点不是空的,则文本将“附加”到现有内容中。如何清空节点的文本内容并在一行中追加新文本。

设置:


这将用新值覆盖现有内容。

如doub1ejack所述

$doc->getElementsByTagName("title")->item(0)->nodeValue = $titleText;
如果
$titleText=“&在Node::nodeValue中不允许”,将给出错误信息

因此,更好的解决方案是

// clear the existing text content
$doc->getElementsByTagName("title")->item(0)->nodeValue = "";

// then create new TextNode
$doc->getElementsByTagName("title")->item(0)->appendChild($doc->createTextNode($titleText));

但是如果这些字符串中有一个非xml安全的字符,这不会失败吗?我假设这就是OP使用
createTextNode()
的原因。这将清除一个旧节点并添加另一个节点,留下两个节点。最好创建新节点并使用它替换旧节点
// clear the existing text content
$doc->getElementsByTagName("title")->item(0)->nodeValue = "";

// then create new TextNode
$doc->getElementsByTagName("title")->item(0)->appendChild($doc->createTextNode($titleText));