By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,949 Members | 1,827 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,949 IT Pros & Developers. It's quick & easy.

PHP Loop with appendChild for XML

P: 16
I have a XML file with multiple <product> ... </product>
I want to have a php file that adds a child to each product.
I'm using the following php code for this:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.     $xdoc = new DomDocument;
  3.     $xdoc->Load('test.xml');
  4.     $product = $xdoc->getElementsByTagName('product')->item(0);
  5.     $newElement = $xdoc ->createElement('store');
  6.     $txtNode = $xdoc ->createTextNode ("admin");
  7.     $newElement -> appendChild($txtNode);
  8.     $product -> appendChild($newElement);
  9.     $test = $xdoc->save("test2.xml");
  10. echo "<B>Data Added<B>"
  11. ?>
This code adds <store>admin</store> only to the first product element because I have item(0) and then creates my second xml file. I tried to make a loop and change the 0 to a variable and use the loop to increase the number, so that it adds "<store>admin</store>" to all products, but I can't figure it out.

Any idea how this can be done?

Thanks in advance...
Aug 28 '08 #1
Share this Question
Share on Google+
2 Replies

Expert Mod 5K+
P: 8,639
You could go a totally different way and use a xsl stylesheet to do that.
Aug 28 '08 #2

Expert 5K+
P: 5,058

You could use a foreach loop.
Expand|Select|Wrap|Line Numbers
  1. $products = $xdoc->getElementsByTagName('product');
  2. foreach($products as $_product) {
  3.   // Create your $newElement
  4.   $_product->appendChild($newElement);
  5. }
Aug 28 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.