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?
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With