Search code examples
phpxpathsimplexmlunset

PHP, simplexml, Delete: Please tell me why the first variant is not working


I hope you can help me on this one:

I want to delete an xml node via unset. I have two variants of how this could be done, but only one is working. Please tell me whats the difference or why only the second variant is working.

So when using the first variant the print_r() function gives back the whole xml file with the image 'Hansio' that should have been deleted. But when using the second variant the image is deleted!

(You can actually copy the whole php code into a file as well as the xml file text - and test it right away - no changes are required - except commenting one variant out of course.)

PHP File:

<?php

$galleries = new SimpleXMLElement('galleries.xml', NULL, TRUE);

/*Variant 1: NOT WORKING_____________________________________________________________*/

$image = $galleries->xpath("//galleries/gallery[@name='gallery']/image[@name='Hansio']");
unset($image[0]);


/*Variant 2: WORKING BUT NOT SO CONVENIENT___________________________________________*/

foreach($galleries->xpath("//galleries/gallery[@name='gallery']/image[@name='Hansio']") as $image)
{
    unset($image[0]);
}

print_r($galleries);

?>

XML File:

<?xml version="1.0" encoding="utf-8"?>

<galleries>
    <gallery name="gallery">
        <image name="image name 1"/>
        <image name="image name 2"/>
        <image name="Hansio"/>
        <image name="image name 4"/>
    </gallery>
</galleries>

Solution

  • The first variant doesn't work because you are unsetting an element of a newly created array, the SimpleXML element isn't touched at all. Try

    unset($image[0][0]);