1

Is there a way to use repeated child elements in DOMDOCUMENT in PHP? In my case, the Billing and Shipping information will always be the same. For example:

$fullname = "John Doe";
$xml = new DOMDocument();
$xml_billing = $xml->createElement("Billing");
$xml_shipping = $xml->createElement("Shipping");
$xml_fullname = $xml->createElement("FullName");
$xml_fullname->nodeValue = $fullname;
$xml_billing->appendChild($xml_fullname);
$xml_shipping->appendChild($xml_fullname);

However, in this case, it removes the element from Billing and leaves it only in Shipping.

hakre
  • 193,403
  • 52
  • 435
  • 836
carver3
  • 13
  • 3

1 Answers1

4

It might not be obvious for you, but if you append the same element to another parent it is moved around in a DOMDocument.

You can prevent that easily by using the created FullName element as a prototype and clone it for the append operation:

$xml_billing->appendChild(clone $xml_fullname);
$xml_shipping->appendChild(clone $xml_fullname);

This then does what you were trying to achieve if I read your question right.


And another hint as I just see it: The following two lines:

$xml_fullname = $xml->createElement("FullName");
$xml_fullname->nodeValue = $fullname;

You can write as one:

$xml_fullname = $xml->createElement("FullName", $fullname);

Hope this helps.

hakre
  • 193,403
  • 52
  • 435
  • 836
  • ((another question, leveraging the context)) The use of `clone` is equivalent to importNode, `$xml_billing->appendChild( $xml_billing->ownerDocument->importNode( $xml_fullname) )`? Or there are some difference? – Peter Krauss Sep 27 '13 at 22:48
  • Thank you hakre for the clarification! – carver3 Sep 28 '13 at 00:20
  • @PeterKrauss: Good question. I don't think so because `importNode()` does allow to take a node from a *different* document whereas in this example clone is used on an element from the *same* document. – hakre Sep 28 '13 at 06:10