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?

4

1 回答 1

1

你快到了,只需稍作调整:

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

看到它工作:http ://codepad.viper-7.com/ZVXs4O

这需要 PHP >= 5.4。
要了解其背后的一些理论:在 PHP 的 SimpleXML 中删除具有特定属性的子项 --> 请参阅 hakre 的答案。

PS:记得更改<number_of_gr>- 或从 XML 中删除此节点,因为您始终可以通过...获取此编号

$groups = $xml->xpath("//group");
$numberofgroups = count($groups);
于 2013-08-07T17:36:55.480 回答