Pranshu Jain
Pranshu Jain

Reputation: 570

How to delete a particular XML child node based on their value

I have an XML structure like this:

<document>
    <sliderimage>
        <images>click.bmp</images>
        <images>error_inotherpluginupload.JPG</images>
        <images>dddd.jpg</images>
        <images>Sunset123.jpg</images>
        <images>Water lilies.jpg</images>     
    </sliderimage>
</document>

And I'm showing these images like this:

This is how I'm showing the images

Code for fetching images you can see here :

<?php
    $usernmeforxml = $_SESSION['username'];
    $xmlpath = SITE_URL . "xml/" . $usernmeforxml . "/test.xml";
    $xml = simplexml_load_string(file_get_contents($xmlpath));
    $sliderimagesinner = $xml->sliderimage->images;
    $imagenum = count($sliderimagesinner);
?>
</br>
<?php
    for ($i = 0; $i < $imagenum; $i++)
    {
?>
    <a class="thumbnail" href="#thumb">
        <img src="../slider_images/<?php 
            echo $sliderimagesinner[$i]; 
        ?>" width="120" height="70" />
        <span>
            <img src="../slider_images/<?php 
                echo $sliderimagesinner[$i]; 
            ?>" width="500" height="350" />
        </span>
    </a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<?php
    }   
?>

Now i want to delete the image by adding a "delete" button on my images. When clicked, that image node should be deleted from the above XML file.

All things are dynamic, so it would be very helpful if anyone can help me regarding this.

Upvotes: 3

Views: 480

Answers (1)

user1452962
user1452962

Reputation: 386

$usernmeforxml=$_SESSION['username'];
$xmlpath=SITE_URL."xml/".$usernmeforxml."/test.xml";
$xml = simplexml_load_file($xmlpath);   
if($_GET['remove'] == 'true') {
    $myValue = $_GET['file'];
    $xel_array = $xml->xpath("//images[text()='" . $myValue . "']");
    //edited - forgot to double [0]
    unset($xel_array[0][0]);
    file_put_contents($xmlpath, $xml->asXML());
}

and a link like

<a href="_your_page.php?remove=true&file=your_file_name">remove</a>

should do the trick.

Upvotes: 3

Related Questions