0

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");
hakre
  • 193,403
  • 52
  • 435
  • 836
Sameeksha Kumari
  • 1,158
  • 2
  • 16
  • 21
  • Why `$index = $index + 1;` and what do you do if the condition is never found? Look into your code what happens then, you have already a logical flaw in the code, regardless of some technical knowledge about which method exactly to use. First fix the logical flaws, they are most often hurting more. – hakre Oct 26 '13 at 18:42
  • Hi, actually in this code would be caught only when there is a matching id. But yes, still it should be check. – Sameeksha Kumari Oct 27 '13 at 09:05

2 Answers2

3

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

Community
  • 1
  • 1
Floh
  • 31
  • 2
2

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]);
  • that xpath selects all <item>-nodes with both 0 in their children <qty> and <qtyonhold>
  • loop through the array $items with foreach and use the unset-syntax explained above.

see it working: http://codepad.viper-7.com/Hae4vY

Community
  • 1
  • 1
michi
  • 6,565
  • 4
  • 33
  • 56