How to replace the text of a node using DOMDocument

Salman A picture Salman A · May 14, 2011 · Viewed 41.1k times · Source

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

$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.

Answer

lonesomeday picture lonesomeday · May 14, 2011

Set DOMNode::$nodeValue instead:

$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.