Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP SimpleXML: Remove items with for

Tags:

php

xml

simplexml

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

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

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]);
    }

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

What's wrong?

like image 360
thom Avatar asked Jan 20 '23 17:01

thom


2 Answers

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.

So, you can do that :

<?php

$items = $this->simpleXML->xpath('/rss/channel/item');
foreach ($items as $item) {
    $node = dom_import_simplexml($item);
    $node->parentNode->removeChild($node);
}
like image 172
Xavier Barbosa Avatar answered Jan 28 '23 16:01

Xavier Barbosa


You're currently only, as you know, unsetting the item from the array.

To get the magical unsetting to work on the SimpleXMLElement, you have to either do as Xavier Barbosa suggested or give PHP a little nudge into firing off the correct unsetting behaviour.

The only change in the code snippet below is the additions of [0]. Heavy emphasis on the word magical.

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

With that said, I would recommend (as Xavier and Josh have) moving into DOM-land for manipulating the document.

like image 31
salathe Avatar answered Jan 28 '23 15:01

salathe