Adding an item multiple times in a DOMDocument

Is there a way to use duplicate children in DOMDOCUMENT in PHP? In my case, the billing and delivery 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, he removes the item from Billing and leaves it only in Shipping.

+1
php domdocument
source share
1 answer

This may not be obvious to you, but if you add the same element to another parent element, it will be moved to the DOMDocument .

This can be easily prevented by using the created FullName element as a prototype and clone it for the add operation:

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

This does what you tried to achieve if I read your question correctly.


And another hint that I just see: the following two lines:

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

You can write one:

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

Hope this helps.

+1
source share

All Articles