如何使用DOMDocument替换节点的文本 [英] How to replace the text of a node using DOMDocument
本文介绍了如何使用DOMDocument替换节点的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码,用于将现有XML文件或字符串加载到DOMDocument对象中:
This is my code that loads an existing XML file or string into a DOMDocument object:
$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));
我需要覆盖标题,描述和链接标记内的值.上面代码中的最后三行是我这样做的尝试;但似乎如果节点不为空,则文本将附加"到现有内容.如何清空节点的文本内容并在一行中添加新文本.
I need to overwrite the value inside the title, description and link tags. The Last three lines in the above code are my attempt at doing so; but seems like if the nodes are not empty then the text will be "appended" to existing content. How can I empty the text content of a node and append new text in one line.
推荐答案
设置 DOMNode::$nodeValue
代替:
$doc->getElementsByTagName("title")->item(0)->nodeValue = $titleText;
$doc->getElementsByTagName("description")->item(0)->nodeValue = $descriptionText;
$doc->getElementsByTagName("link")->item(0)->nodeValue = $linkText;
这会用新值覆盖现有内容.
This overwrites the existing content with the new value.
这篇关于如何使用DOMDocument替换节点的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文