How to Add a Child to an Existing XML Node Using PHP?

Find out how to create a new child node in an existing XML node using PHP

To add a child node to an existing XML node using PHP SimpleXMLElement object, you need to select the node you wish to add the new child node to and then call the SimpleXMLElement::addChild() method on it. For example:

$xml = new SimpleXMLElement($xmlStr);
$xml->parentNode->addChild('nodeName', 'value');
// ...

For example, let's suppose you have the following XML:

$xmlStr =<<<XML
<?xml version="1.0"?>
    <message>
        <to>[email protected]</to>
        <subject>Hello World!</subject>
        <body>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</body>
        <attachments>
            <file>1.jpg</file>
        </attachments>
    </message>
XML;

To add a child to the existing "<attachments>" node and save the changes, you would do the following:

$xml = new SimpleXMLElement($xmlStr);

// add new node to existing `attachments` node
$xml->attachments->addChild('file', '2.jpg');

// save changes
$xml->asXML();

This would result in the following XML:

<?xml version="1.0"?>
<message>
    <to>[email protected]</to>
    <subject>Hello World!</subject>
    <body>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</body>
    <attachments>
        <file>1.jpg</file>
        <file>2.jpg</file>
    </attachments>
</message>

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