This code only adds 3 out of 5 name nodes. Why is this? Here is the original XML: It has 5 name nodes.
<?xml version='1.0'?> <products> <product> <itemId>531670</itemId> <modelNumber>METRA ELECTRONICS/MOBILE AUDIO</modelNumber> <categoryPath> <category><name>Buy</name></category> <category><name>Car, Marine & GPS</name></category> <category><name>Car Installation Parts</name></category> <category><name>Deck Installation Parts</name></category> <category><name>Antennas & Adapters</name></category> </categoryPath> </product> </products>
Then run this PHP code. which supposedly adds ALL name nodes to the node product.
<?php // load up your XML $xml = new DOMDocument; $xml->load('book.xml'); // Find all elements you want to replace. Since your data is really simple, // you can do this without much ado. Otherwise you could read up on XPath. // See http://www.php.net/manual/en/class.domxpath.php //$elements = $xml->getElementsByTagName('category'); // WARNING: $elements is a "live" list -- it going to reflect the structure // of the document even as we are modifying it! For this reason, it's // important to write the loop in a way that makes it work correctly in the // presence of such "live updates". foreach ($xml->getElementsByTagName('product') as $product ) { foreach($product->getElementsByTagName('name') as $name ) { $product->appendChild($name ); } $product->removeChild($xml->getElementsByTagName('categoryPath')->item(0)); } // final result: $result = $xml->saveXML(); echo $result; ?>
The end result is this, and it adds only 3 name nodes:
<?xml version="1.0"?> <products> <product> <itemId>531670</itemId> <modelNumber>METRA ELECTRONICS/MOBILE AUDIO</modelNumber> <name>Buy</name> <name>Antennas & Adapters</name> <name>Car Installation Parts</name> </product> </products>
Why is it just adding 3 name nodes?
source share