Home » Php » PHP DOMDocument question: how to replace text of a node?

PHP DOMDocument question: how to replace text of a node?

Posted by: admin December 5, 2017 Leave a comment


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

$doc = new DOMDocument();
$doc->formatOutput = true;

if(is_file($filePath)) {
else {
    $doc->loadXML('<rss version="2.0"><channel><title></title><description></description><link></link></channel></rss>');

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 once the file is created, the text will be “appended” to existing one. How can I empty the text content of a node (DOMNode I guess) and append new text in one line.


PS: If there is a built in alternate (a class or library) that requires less LOC to do simple tasks such as this one then do let me know.


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.


as doub1ejack mentioned

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

will give error if $titleText = "& is not allowed in Node::nodeValue";

So the better solution would be

// clear the existing text content
$doc->getElementsByTagName("title")->item(0)->nodeValue = "";

// then create new TextNode

Leave a Reply

Your email address will not be published. Required fields are marked *