这是我的代码,它将现有的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));
我需要覆盖标题,描述和链接标记内的值。上面代码中的最后三行是我尝试这样做的;但似乎如果节点不为空,则文本将“附加”到现有内容。如何清空节点的文本内容并在一行中附加新文本。
答案 0 :(得分:46)
设置DOMNode::$nodeValue
代替:
$doc->getElementsByTagName("title")->item(0)->nodeValue = $titleText;
$doc->getElementsByTagName("description")->item(0)->nodeValue = $descriptionText;
$doc->getElementsByTagName("link")->item(0)->nodeValue = $linkText;
这会使用新值覆盖现有内容。
答案 1 :(得分:5)
正如doub1ejack所提到的那样
$doc->getElementsByTagName("title")->item(0)->nodeValue = $titleText;
$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));