You can add a new node to an XML document (or string) using PHP SimpleXMLElement
object like so:
$xml = new SimpleXMLElement($xmlStr); $xml->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 new node to the XML, you would do the following:
$xml = new SimpleXMLElement($xmlStr); // add new node to the end $xml->addChild('from', '[email protected]'); // 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> <from>[email protected]</from> </message>
It is also possible to add attributes or nested child nodes to the new child node you intend to add.
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.