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

佐手、 提交于 2019-12-12 23:08:01

问题


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>

回答1:


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]);


来源:https://stackoverflow.com/questions/13002313/php-simplexml-delete-please-tell-me-why-the-first-variant-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!