1

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user2660877
  • 13
  • 1
  • 3

1 Answers1

1

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);
Community
  • 1
  • 1
michi
  • 6,565
  • 4
  • 33
  • 56
  • 1
    Presumably this only requires PHP >= 5.4 because of the `foo()[0]` syntax? If so, for anyone on an older version: `$delgroup = $xml->xpath("//group[@id='".$_GET['group']."'"); unset($delgroup[0][0]);` works just as well. – IMSoP Aug 07 '13 at 20:36
  • @IMSoP Yes, array dereferencing is PHP >= 5.4. Thanks for the addition! – michi Aug 07 '13 at 22:22