Reputation: 323
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();
Upvotes: 0
Views: 1994
Reputation: 16107
The PHP
library for DOM
manipulation is object oriented not functional/ procedural.
You don't generate a DOMDocument
then use it everywhere to call every method, each node has it's own methods. You use the DOMDocument to creat new elements but after that you use the element's methods to append an element to another element.
Try to look at the following classes DOMDocument, DOMElement, DOMAttr and DOMText, and their common ancestor DOMNode from the PHP docs. That should clear some things up about which kind of object you're dealing with and what methods you can use with it.
$xmlFile = '/path/to/filename.xml';
$xmlString = file_get_contents($xmlFile);
$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xmlString);
$books = $dom->getElementsByTagName('book'); // Find Books
foreach ($books as $book) //go to each book 1 by 1
{
$price = $dom->createElement('price');
$book->appendChild($price);
$text = $dom->createTextNode('20');
$price->appendChild($text);
}
$dom->saveXML();
Upvotes: 2