SimpleXML 删除节点 [英] SimpleXML remove nodes

查看:27
本文介绍了SimpleXML 删除节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个只运行一次的 foreach 循环,它让我难住了.

I've got a foreach loop that is only running once and it has me stumped.

1:我加载一组状态值(请求"、删除"或已购买")

1: I load an array of status values (either "request", "delete", or "purchased")

2:然后我加载一个 xml 文件并需要遍历代码"节点并更新它们的状态,但是如果新代码是删除"我想在移动到下一个之前将其删除

2: I then load an xml file and need to loop through the "code" nodes and update their status, BUT if the new code is "delete" I want to remove it before moving onto the next one

XML 结构是....

XML structure is....

<content>
.... lots of stuff
<codes>
<code date="xxx" status="request">xxxxx</code>
.. repeat ...
</codes>
</content>

和php代码是...

$newstatus = $_POST['updates'];
$file = '../apps/templates/'.$folder.'/layout.xml';
$xml2 = simplexml_load_file($file);
foreach($xml2->codes->code as $code){
    if($code['status'] == "delete") {
        $dom=dom_import_simplexml($code);
        $dom->parentNode->removeChild($dom);
    }
}
$xml2->asXml($file);

我暂时删除了更新,以便调试删除检查.这一切都有效,但它只删除第一个删除并保留所有其他删除,即使它是一个 foreach 循环??.非常感谢任何帮助.

I've temporarily removed the updating so I can debug the delete check. This all works BUT it only removes the 1st delete and leaves all the other deletes even though it's a foreach loop??. Any help greatly appreciated.

推荐答案

在同一次迭代中多次删除是不稳定的.例如.如果删除第二个元素,则第三个元素变成第二个,依此类推.

Deleting multiple times in the same iteration is unstable. E.g. if you remove the second element, the third becomes the second and so on.

您可以通过先将要删除的元素存储到数组中来防止这种情况:

You can prevent that by storing the elements to delete into an array first:

$elementsToRemove = array();
foreach ($xml2->codes->code as $code) {
    if ($code['status'] == "delete") {
        $elementsToRemove[] = $code;
    }
}

然后根据在迭代时稳定的数组删除元素:

And then you remove the element based on the array which is stable while you iterate over it:

foreach ($elementsToRemove as $code) {
    unset($code[0]);
}

您也可以将 if 条件放入 xpath 查询中,该查询会直接返回数组(请参阅重复问题例如)或使用 iterator_to_array().

You could also put the if-condition into an xpath query which does return the array directly (see the duplicate question for an example) or by making use of iterator_to_array().

这篇关于SimpleXML 删除节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆