views:

25

answers:

1

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);
$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();
?>`

Modifying $el2 is still possible because it is deep-copied and added to $el3's DOM. $el1 however still points to $doc2/$el2's DOM and any changes are not reflected in $el3's DOM.

Are there any generic ways to to directly point $el1 to the right node in $el3's DOM?

A: 
$el2 = $doc3->importNode($el2, true);

Here you make a deep copy of $el2, i.e. you also make a copy of $e1 which you appended to $e2. When you later change the node value of $e1 it doesn't effect the clone/deep copy of $e1.

VolkerK
Ah. I see. $el2 is a deep copy which is actually added to $el3. As a result modifying $el2 reflects also in $el3's DOM.In that case I need some generic way to set $el1 to the corresponding node in $el3's DOM. I edited the original question.
Robbie Groenewoudt
Is the result a _valid_ XHTML document anyway?
VolkerK