I have this XML file with many child nodes, and I have this PHP code, but this is only adding the first node. I want to add the whole XML in name is node child.
Current XML:
<root> <result> <node> <someting>asdasd</something> </node> <node> <someting>asdasd</something> </node> </result> <error/> </root>
What I need:
<root> <result> <node> <someting>asdasd</something> <Shipping_Cost>9</Shipping_Cost> </node> <node> <someting>asdasd</something> <Shipping_Cost>9</Shipping_Cost> </node> </result> <error/> </root>
Current PHP code:
function fn_add_shipping($xmlFileToLoad, $destination) { $xmlFileToLoad = 'shipping.xml'; $dom = new DOMDocument(); $dom->load($xmlFileToLoad); $shipping = $dom->getElementsByTagName('node')->item(0); $ship = $dom->createElement('Shipping_Cost', '9'); $shipping->appendChild($ship); $dom->save($destination); return $destination; }
Advertisement
Answer
Sorry, I misunderstood your question. I did not realize the 2nd XML file was what you wanted to get as a result of the PHP method. Now that I see that, I think I understand where your problem is. You are only calling the append function one time. You need to loop through each node, calling the append each time before outputting the results to the destination XML file.
Perhaps something like this:
function fn_add_shipping($xmlFileToLoad, $destination) { $xmlFileToLoad = 'shipping.xml'; $dom = new DOMDocument(); $dom->load($xmlFileToLoad); $shipping = $dom->getElementsByTagName('node'); for ($x=0; $x<$shipping->length; $x++) { $ship = $dom->createElement('Shipping_Cost', '9'); $shipping[$x]->appendChild($ship); } $dom->save($destination); return $destination; }