繁体   English   中英

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

[英]How to replace the text of a node using DOMDocument

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

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

改为设置DOMNode::$nodeValue

$doc->getElementsByTagName("title")->item(0)->nodeValue = $titleText;
$doc->getElementsByTagName("description")->item(0)->nodeValue = $descriptionText;
$doc->getElementsByTagName("link")->item(0)->nodeValue = $linkText;

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

正如 doub1ejack 提到的

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

如果$titleText = "& is not allowed in Node::nodeValue";会报错$titleText = "& is not allowed in 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));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM