You can add a new node with children to an existing node in an XML document (or string) using PHP SimpleXMLElement
object by following these steps:
- Use
SimpleXMLElement::addChild()
to add the new node and assign it to a variable; - Call the
SimpleXMLElement::addChild()
method on the variable (from the last step) to add a child element to the new node.
For example, let's suppose you have the following XML of customers:
$xmlStr =<<<XML
<?xml version="1.0"?>
<customers>
<customer>
<name>John Doe</name>
<age>24</age>
</customer>
<customer>
<name>Jane Doe</name>
<age>29</age>
</customer>
</customers>
XML;
To add a new customer node with name
and age
child nodes to the XML, you would do the following:
$xml = new SimpleXMLElement($xmlStr);
// add new `customer` node
$newNode = $xml->addChild('customer');
// add child nodes to the new `customer` node
$newNode->addChild('name', 'Bruce Wayne');
$newNode->addChild('age', '39');
// save changes
$xml->asXML();
This would result in the following XML:
<?xml version="1.0"?>
<customers>
<customer>
<name>John Doe</name>
<age>24</age>
</customer>
<customer>
<name>Jane Doe</name>
<age>29</age>
</customer>
<customer>
<name>Bruce Wayne</name>
<age>39</age>
</customer>
</customers>
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.