Reputation: 1264
I am trying to delete an XML node using SimpleXmlElement
.
But there is no change in the XML file after I run this code. It should work but unset
does not make any change in the file:
$xml = new SimpleXMLElement('goods.xml', NULL, TRUE);
$items = $xml->xpath('/items/item');
for ($i =0; $i < sizeof($items); $i++)
{
if ($items[$i]->qty == 0 and $items[$i]->qtyonhold == 0)
{
$index = $i;
}
}
$index = $index + 1;
var_dump($items[$index]);
unset($items[$index]);
$xml->asXML("goods.xml");
Upvotes: 0
Views: 177
Reputation: 6625
use
unset($items[$index][0]);
There is a very good explanation on why this is working this way on SO by hakre
, look it up.
Apart from that, you could simplify your code and do everything in just 3 lines:
$xml = simplexml_load_string($x); // assume XML in $x
$items = $xml->xpath("/items/item[qty='0' and qtyonhold='0']");
foreach ($items as $item) unset($item[0]);
xpath
selects all <item>
-nodes with both 0
in their children <qty>
and <qtyonhold>
$items
with foreach
and use the unset
-syntax explained above.see it working: http://codepad.viper-7.com/Hae4vY
Upvotes: 2
Reputation: 31
You're assigning the items xpath to the $items variable. You remove the index from there correctly, but you're displaying the $xml variable. $items is just like a copy of the xpath of the $xml object. So actually you would need to remove that index from the $xml variable itself.
I just found a good explained solution here on this platform: https://stackoverflow.com/a/262556/2922852
Upvotes: 3