Search code examples
phpdomdocument

PHP DOMDocument: may a text node be reused?


I have following code:

    $doc = new \DOMDocument('1.0', 'UTF-8');
    $doc->formatOutput = true;

    $element = $doc->createElement('ROOT');
    $root = $doc->appendChild($element);

    $textNode = $doc->createTextNode('I should be in both nodes');


    $element = $doc->createElement('FIRST');
    $first = $root->appendChild($element);
    $first->appendChild($textNode);

    $element = $doc->createElement('SECOND');
    $second = $root->appendChild($element);
    $second->appendChild($textNode);


    var_dump($doc->saveXML($root));

What I don't understand is why the output is this:

<ROOT>
  <FIRST/>
  <SECOND>I should be in both nodes</SECOND>
</ROOT>

How come the FIRST element does not contain the text? Did the SECOND one steal it? :) Because if I remove the code part creating the SECOND element, the FIRST one gets its text node as expected.


Solution

  • A node can only have 1 parent, so as soon as you add it to another node, that is where it will stay.

    You can easily clone the node using cloneNode(), but as the name implies - it's not the same node but a copy. If you change the following line to...

    $first->appendChild($textNode->cloneNode(true));
    

    You will get...

    <ROOT>
      <FIRST>I should be in both nodes</FIRST>
      <SECOND>I should be in both nodes</SECOND>
    </ROOT>