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.
<book>
<title>title 1</title>
<author>author 1</author>
</book>
<book>
<title>title 2</title>
<author>author 2</author>
</book>
Expected output:
<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>
This is what I have written so far:
$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();