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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6001923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:08:49  来源:igfitidea点击:

How to replace the text of a node using DOMDocument

phpxmlrssdomdocumentnodes

提问by Salman A

This is my code that loads an existing XML file or string into a DOMDocument object:

这是我将现有 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));

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.

我需要覆盖标题、描述和链接标签内的值。上面代码中的最后三行是我尝试这样做的;但似乎如果节点不为空,则文本将“附加”到现有内容中。如何清空节点的文本内容并在一行中附加新文本。

回答by lonesomeday

Set DOMNode::$nodeValueinstead:

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.

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

回答by Raaghu

as doub1eHyman mentioned

正如 doub1eHyman 提到的

$doc->getElementsByTagName("title")->item(0)->nodeValue = $titleText;

will give error if $titleText = "& is not allowed in Node::nodeValue";

会报错,如果 $titleText = "& is not allowed in Node::nodeValue";

So the better solution would be

所以更好的解决方案是

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

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