DOMNode reference doesn't work anymore after appending it to another element twice
- by Robbie Groenewoudt
Hi, I'm using the a wrapper around the PHP5-class DOMDocument to generate my HTML. This makes it easy to modify the HTML by using the DOM.
An example is creating element #1 and adding it to the element #2 and still be able to modify element #1 directly.
A problem arises however with the following:
Element #1 is added to element #2
Element #2 is added to element #3
Element #1 is modified but no changes are visible in the DOM of element #3 (which contains #1 and #2)
A simplified sample code:
<?php
$doc1 = new DOMDocument();
$el1 = $doc1->createElement('h1', 'Hello');
$doc1->appendChild($el1);
$doc2 = new DOMDocument();
$el2 = $doc2->createElement('h2', 'World');
$doc2->appendChild($el2);
$doc3 = new DOMDocument();
$el3 = $doc3->createElement('h3', 'Today');
$doc3->appendChild($el3);
// Import el1 into el2
$el1 = $doc2->importNode($el1, true);
$el2->appendChild( $el1 );
$doc1 = $doc2;
// Import el2 into el3
$el2 = $doc3->importNode($el2, true);
//$el1 = $doc3->importNode($el1, true); Necessary?
$el3->appendChild($el2);
$doc2 = $doc3;
// Modify el1
$el1->nodeValue = "Boo"; // This doesn't work?
//$el2->nodeValue = "Boo"; // Changing element2 or 3 works...
// Display result
echo $doc3->saveHTML();
?>`
Any idea's on why modifying $el1 won't work? (While $el2 works fine) Or an easy way to set $el1 to the right element?