How to Add a New Node With Children to an Existing XML Node Using PHP?

Find out how to add a child with children to an XML node in PHP

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:

  1. Use SimpleXMLElement::addChild() to add the new node and assign it to a variable;
  2. 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>

Hope you found this post useful. It was published . Please show your love and support by sharing this post.