user2660877
user2660877

Reputation: 13

How can I delete a child from an XML file via simplexml?

I've got the following xml file:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <number_of_gr>
        3
    </number_of_gr>
    <group id="0">
        <name>Admins</name>
        <backend>1</backend>
        <every_plugin_feature> 1 </every_plugin_feature>
    </group>
    <group id="1">
        <name>Users</name>
        <backend>0</backend>
        <every_plugin_feature>0</every_plugin_feature>
    </group>
    <group id="2">
        <name>Moderators</name>
        <backend>0</backend>
        <every_plugin_feature>0</every_plugin_feature>
    </group>
</root>

For Example: I want to delete the group with the id="0". But I don't know how to delete a child with specified attribute in simplexml.

I've tried this code:

<?php
$xml = simplexml_load_file("../xml/groups.xml");
$delgroup = $xml->xpath("/root/group[@id='".$_GET['group']."'");
unset($delgroup);
$xml-> asXML("../xml/groups.xml");
?>

But it doesn't work.

After the process, I'll fill the gap with the id=1, but I can do it without help.

My question is: How to delete the specified group?

Upvotes: 1

Views: 83

Answers (1)

michi
michi

Reputation: 6625

You are almost there, just a little tweak:

$delgroup = $xml->xpath("//group[@id='".$_GET['group']."'")[0];
unset($delgroup[0]);

see it working: http://codepad.viper-7.com/ZVXs4O

This requires PHP >= 5.4.
To see a bit of theory behind it: Remove a child with a specific attribute, in SimpleXML for PHP --> see hakre's answer.

PS: Remember to change <number_of_gr> - or delete this node from the XML, because you can always get this number by...

$groups = $xml->xpath("//group");
$numberofgroups = count($groups);

Upvotes: 1

Related Questions