dongyi6668 2014-11-30 10:00
浏览 152
已采纳

使用unset()删除XML中的节点; PHP /使用simplexml_load_file

I'm trying to use unset() to delete a node in an XML using PHP and can't figure out what is going on here. It doesn't seem to work correctly and I've seen a lot of other questions of similar nature on here but they don't seem to address this issue directly. Here's what my XML looks like:

<?xml version="1.0" encoding="UTF-8"?>
<data>
    <user>
        <name>Test Name 1</name>
        <email>test@test.com</email>
        <spouse/>
    </user>
    <user>
        <name>Test Name 2</name>
        <email>anotherone@test.com</email>
        <spouse>Test Name 3</spouse>
    </user>
</data>    

My loop that I'm using is like this:

url = 'data/users.xml';
$xml = simplexml_load_file($url);

foreach($xml->user as $theUser){
    if($theUser->email[0]=="test@test.com"){
        echo "test";
        unset($theUser);
    }
}

When the e-mail matches "test@test.com" I want to be able to delete that whole user node. It seems that this should work but I can't figure out why it wouldn't? Any help would be greatly appreciated. Thank you!

  • 写回答

2条回答 默认 最新

  • dongpin6941 2014-12-01 04:10
    关注

    SimpleXML is fine, no need to switch to DOM, unset() is working fine, if you do it right:

    unset($theUser[0]);
    

    see it working: https://eval.in/228773

    However there will be a problem with your foreach() if you delete a node mid-loop.

    I suggest to use xpath() instead of a loop, IMO elegant and the code is much simpler.

    $users = $xml->xpath("/data/user[email='test@test.com']");
    

    will create an array of all <user> with that email-address.

    unset($users[0][0]);
    

    will delete the first user in that array.

    foreach ($users as $user) unset($user[0]);
    

    will delete the whole array.

    see this in action: https://eval.in/228779

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看