DEV Community

Eelco Verbrugge
Eelco Verbrugge

Posted on

4 1

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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →