How to replace the text of a node using DOMDocument

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
$doc->getElementsByTagName("title")->item(0)->appendChild($doc->createTextNode($titleText));