PHP: Find XML node and insert child
domdocument, php, xml
Solution
This should be a start:
$dom = new DOMDocument;
$dom->loadXML($input);
$ids = $dom->getElementsByTagName('id');
foreach ($ids as $id) {
if ($id->nodeValue == '1') {
$child = $dom->createElement('tagname');
$child->appendChild($dom->createTextNode('some text'));
$id->parentNode->appendChild($child);
}
}
$xml = $dom->saveXML();
or something close to it.
Problem
I have an xml document with the following structure: ``` <?xml version="1.0" encoding="UTF-8"?> <items> <item> <id>1</id> <url>www.test.com</url> </item> <item> <id>2</id> <url>www.test2.com</url> </item> </items> ``` I would like to be able to search for a node value, such as the value of 1 for the id field. Then, once that node is found, select the parent node, which would be < item > and insert a new child within. I know the concept of using dom document, but not sure how to do it in this instance.