How to Add an Attribute to an XML Node Using PHP?

Learn how to add an attribute to a node in XML document/string using PHP

You can add an attribute to an XML node by using the SimpleXMLElement::addAttribute() method in PHP, for example, like so:

$xml = new SimpleXMLElement($xmlStr);
$xml->addAttribute('name', 'value');
// ...

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

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

To add an attribute to the XML, you would do the following:

$xml = new SimpleXMLElement($xmlStr);

// add attribute to first node
$xml->addAttribute('sent', true);

// add attribute to existing `to` node
$xml->to->addAttribute('name', 'John Doe');

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

This would result in the following XML:

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

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