I have a simple XML string:
$sample = new SimpleXMLElement('<root><parent><child1></child1></parent></root>');
and i try to find node with xpath() and add child to this node.
$node = $sample->xpath('//parent');
$node[0]->addChild('child2');
echo $sample->asXML();
As you see child2
is added as a child of child1
, not as a child of parent
.
<root>
<parent>
<child1>
<child2></child2>
</child1>
</parent>
</root>
But if i change my XML, addChild() works great. This code
$sample = new SimpleXMLElement('<root><parent><child1><foobar></foobar></child1></parent></root>');
$node = $sample->xpath('//parent');
$node[0]->addChild('child2');
echo $sample->asXML();
returns
<root>
<parent>
<child1>
<foobar></foobar>
</child1>
<child2>
</child2>
</parent>
</root>
So i have two questions:
- Why?
- How can i add
child2
as a child ofparent
, ifchild1
has no child?