PHP SimpleXML:使用 for 删除项目 [英] PHP SimpleXML: Remove items with for

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

问题描述

我可以使用以下命令从 simpleXML 元素中删除一个项目:

I just can remove an item from a simpleXML element with:

unset($this->simpleXML->channel->item[0]);

但我不能用 a for:

but I can't with the a for:

    $items = $this->simpleXML->xpath('/rss/channel/item');
    for($i = count($items); $i > $itemsNumber; $i--) {
        unset($items[$i - 1]);
    }

从 $items 中删除了一些项目(Netbeans Debug 可以确认这一点)但是当我再次获取路径时(/rss/channel/item)没有任何内容被删除.

some items are removed from $items (Netbeans Debug can confirm that) but when I get the path again (/rss/channel/item) nothing was deleted.

怎么了?

推荐答案

SimpleXML 不处理节点删除,为此需要使用 DOMNode.令人高兴的是,当您将节点导入 DOMNode 时,这些实例指向同一棵树.

SimpleXML does not handle node deletion, you need to use DOMNode for this. Happily, when you import your nodes into DOMNode, the instances point to the same tree.

所以,你可以这样做:

<?php

$items = $this->simpleXML->xpath('/rss/channel/item');
foreach ($items as $item) {
    $node = dom_import_simplexml($item);
    $node->parentNode->removeChild($node);
}

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

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