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 isnt 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 cant do unset($xml->data->items)
as that would delete everything.
Any ideas much appreciated :-)
It works like this for me. Not
unset($parent);
butunset($parent[0]);
:This works by creating a self-reference to the simplexml-element in
$parent
(or$res[0]
).For a more detailed explanation please see a related answer in the related question Remove a child with a specific attribute, in SimpleXML for PHP.
this works as intended (removing the <b/> element fromt he document) because the __unset() method (or the equivalent in the modules code) is called.
But when you call
unset($parent);
it only removes the object reference stored in $parent, but it doesn't affect the object itself or the document stored in $xml. I'd revert to DOMDocument for this.prints
One way is to import the SimpleXML node into DOMDocument and then remove within DOMDocument. Not really straight forward, but it works:
I'd surely approach this problem as a filtering one - not a removing one.
Thus, copying needed nodes into another string or build up another XML document for that matter. You know what tools you use for such scenarios.
I think this not only solves your problem, but probably keeps your easier to read and understand. Not sure about performance hits, though. Tell us how many nodes you regularly work with.