DEV Community

Eelco Verbrugge
Eelco Verbrugge

Posted on

PHP SimpleXMLElement

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();
Enter fullscreen mode Exit fullscreen mode

This would result in the following output:

<?xml version="1.0"?>
<request>
    <name>John Doe</name>
    <age>50</age>
    <gender>Female</gender>
</request>
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

Output:

<?xml version="1.0"?>
<request>
    <name>John Doe</name>
    <age>50</age>
    <gender>Male</gender>
</request>
Enter fullscreen mode Exit fullscreen mode

That's all folks~

Source: https://coderedirect.com/questions/154676/edit-xml-with-simplexml

Top comments (1)

Collapse
 
syedumairaali profile image
Syed Umair Ali • Edited

You can edit with simplexml

$input = <<<end
<?xml version='1.0' standalone='yes'?>
<documents>
  <document>
    <name>spec.doc</name>
  </document>
</documents>
end;

$xml = new simplexmlelement($input);
$xml->document[0]->name = 'spec.pdf';
$output = $xml->asxml();
Enter fullscreen mode Exit fullscreen mode

Source: Edit Xml With Simplexml