簡體   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