Help | Site Map
Connecting Tech Pros Worldwide
Reply
 
LinkBack Thread Tools
  #1  
Old August 28th, 2008, 06:29 AM
Newbie
 
Join Date: Sep 2007
Location: USA
Posts: 16
Default PHP Loop with appendChild for XML

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...
Reply
  #2  
Old August 28th, 2008, 06:59 AM
Dormilich's Avatar
Expert
 
Join Date: Aug 2008
Location: Leipzig, Germany
Age: 31
Posts: 646
Default

You could go a totally different way and use a xsl stylesheet to do that.
Reply
  #3  
Old August 28th, 2008, 09:55 PM
Atli's Avatar
Moderator
 
Join Date: Nov 2006
Location: Iceland
Age: 22
Posts: 2,777
Default

Hi.

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

Bookmarks

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are Off
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over network members.
Post your question now . . .
It's fast and it's free

Popular Articles