Need help in appending a new child to existing XML in php

Zacharyd

New Member
This is my xml file. I want to add a new element to all books called 'price'. I don't know how to loop through all the books and append a child in them in PHP.Please help.\[code\]<book><title>title 1</title><author>author 1</author></book><book><title>title 2</title><author>author 2</author></book>\[/code\]Expected output:\[code\]<book><title>title 1</title><author>author 1</author><price>20</price></book><book><title>title 2</title><author>author 2</author><price>20</price></book>\[/code\]This is what I have written so far:\[code\] $dom = new DomDocument; $dom->preserveWhiteSpace = FALSE; $dom->loadXML($xmlFile); $books = $dom->getElementsByTagName('book'); // Find Books foreach ($books as $book) //go to each book 1 by 1 { $price = $dom->createElement('price'); $price = $dom->appendChild($price ); $text = $dom->createTextNode('20'); $text = $dom->appendChild($text); } $dom->saveXML();\[/code\]
 
Back
Top