Sal*_*n A 27 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>
<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));
Run Code Online (Sandbox Code Playgroud)
我需要覆盖标题,描述和链接标记内的值.上面代码中的最后三行是我尝试这样做的; 但似乎如果节点不为空,则文本将"附加"到现有内容.如何清空节点的文本内容并在一行中添加新文本.
lon*_*day 47
设置DOMNode::$nodeValue改为:
$doc->getElementsByTagName("title")->item(0)->nodeValue = $titleText;
$doc->getElementsByTagName("description")->item(0)->nodeValue = $descriptionText;
$doc->getElementsByTagName("link")->item(0)->nodeValue = $linkText;
Run Code Online (Sandbox Code Playgroud)
这会使用新值覆盖现有内容.
正如doub1ejack所提到的
$doc->getElementsByTagName("title")->item(0)->nodeValue = $titleText;
Run Code Online (Sandbox Code Playgroud)
如果出现错误 $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));
Run Code Online (Sandbox Code Playgroud)