PHP SimpleXMLElement
Eelco Verbrugge
Posted on November 1, 2021
SimpleXMLElement is part of the PHP core. It's an extention that allows us to create or manipulate XML.
I use addChild()
to layout my XML, but what if you need to edit or replace an element afterworth? There is no editChild()
or replaceChild
to accomplish this, nor could you add a position to a new child. There are many ways to solve this, but according to me... This is the way.
1. Generate XML
To start with, lets create some dummy XML:
$xml = newSimpleXMLElement('<request></request>');
$xml->addChild('name', $name);
$xml->addChild('age', $age);
$xml->addChild('gender', $gender);
$result = $xml->asXML();
This would result in the following output:
<?xml version="1.0"?>
<request>
<name>John Doe</name>
<age>50</age>
<gender>Female</gender>
</request>
2. Edit or replace XML nodes/elements
Now if I would like to change the gender from Female
to Male
, I would edit or replace the value:
$xml->gender[0] = 'Male';
$result = $xml->asXML();
Output:
<?xml version="1.0"?>
<request>
<name>John Doe</name>
<age>50</age>
<gender>Male</gender>
</request>
That's all folks~
Source: https://coderedirect.com/questions/154676/edit-xml-with-simplexml
Posted on November 1, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.