Alex Rivera | Logout

SimpleXML - Remove xpath node

Asked 2010-03-14T13:37:29.507
13

I'm a little confused as to how I can delete a parent node of something which I can find via an xpath search:

$xml = simplexml_load_file($filename);
$data = $xml->xpath('//items/info[item_id="' . $item_id . '"]');
$parent = $data[0]->xpath("parent::*");
unset($parent);

So, it finds the item id, no problems there - but the unset isn't getting rid of this <items> node. All I want to do is remove the <items>...</items> for this product. Obviously, there are loads of <items> nodes in the xml file so it can't do unset($xml->data->items) as that would delete everything.

Any ideas much appreciated :-)

Edit
Report

1 Answer

2

One way is to import the SimpleXML node into DOMDocument and then remove within DOMDocument. Not really straight forward, but it works:

$xml = simplexml_load_file($filename);

$result = $xml->xpath("/cardsets/cardgroup");

foreach ($result as $el)
{
    if ($el['id'] == $id)
    {
        $domRef = dom_import_simplexml($el);
        $domRef->parentNode->removeChild($domRef);
        $dom = new DOMDocument('1.0');
        $dom->preserveWhiteSpace = false;
        $dom->formatOutput = true;
        $dom->loadXML($xml->asXML());
        $dom->save($filename);
        break;
    }
}
answered 2010-11-19T16:06:06.010

Your Answer