How to Add a Child to 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>

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.