PHP SimpleXMLElement

eelcoverbrugge

Eelco Verbrugge

Posted on November 1, 2021

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

💖 💪 🙅 🚩
eelcoverbrugge
Eelco Verbrugge

Posted on November 1, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related