PHP, simplexml, Delete: please tell me why the first option doesn't work

I hope you can help me with this:

I want to remove xml node via unset. I have two options on how to do this, but only one works. Please tell me what is the difference or why only the second option works.

Thus, when using the first option, the print_r () function returns the entire XML file with the "Hansio" image to be removed. But when using the second option, the image is deleted!

(In fact, you can copy all the PHP code into a file, as well as the text of the xml file - and test it right away - no changes are required), except, of course, commenting one option.)

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>

      

+1


source to share


1 answer


The first option doesn't work because you are deleting the element of the newly created array, the SimpleXML element is not affected at all. Try



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

      

0


source







All Articles