30

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.

Salman A
  • 262,204
  • 82
  • 430
  • 521

2 Answers2

54

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.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • 7
    But won't this fail if there is a non xml-safe character in these strings? I assumed that is why the OP is using `createTextNode()`. – doub1ejack Mar 24 '15 at 20:16
11

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));
Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
Raaghu
  • 1,956
  • 1
  • 19
  • 17
  • 4
    this clears an old node and adds another one, leaving two nodes. It's better to create the new node and use it to replace the old one – patrick Nov 27 '15 at 14:18