Jakub Folejtar Jakub Folejtar - 1 month ago 5
PHP Question

Append child to xml based on attribute of the parent node in php

I would like to ask, how to easily append new node to the end of found node in php.
Lets say I have xml like this:

<Root>
<child id=1>
<text>smth</text>
</child>
</Root>


I want to find the child element with id 1 and then append another node as last.
I was trying to find an answer, but it either answer how to find it, or how to write into it, unfortunately I was not able to put it together.

I would be really happy if someone can help me with this.

Answer

You can use the xpath to find the relevant node (based on the id) and then use the addChild to add new child-node to the node you just found:

$str =<<< END
<Root>
    <child id="1">
        <text>smth</text>
    </child>
</Root>
END;

$result = simplexml_load_string($str);

$child = $result->xpath("*[@id='1']")[0];
$child->addChild('text', 'node value');

// The part from here is only to make the output pretty-xml
// instead you can just use $result->saveXML()
$dom = new DOMDocument("1.0");
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($result->saveXML());
var_dump($dom->saveXML());

The output will be:

string(115) "<?xml version="1.0"?>
<Root>
    <child id="1">
        <text>smth</text>
        <text>node value</text>
    </child>
</Root>
"
Comments