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.
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.