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>john@doe.com</to>
<from>jane@doe.com</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">john@doe.com</to>
<from>jane@doe.com</from>
<subject>Hello World!</subject>
<body>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</body>
<attachments>
<file>1.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.