Question

I’m trying to figure out how to remove a child with a specific attribute selected (filename). I have PHP displaying an XML file on a page that loads images. If someone where to click on any image or hit the delete button -

<a href=""><img src="' . $child['src'] . '" alt="gallery image" />Delete me</a>

it would know where to find in the XML file and delete it.

Here what loads and displays my XML file:

<?php 
$xml = simplexml_load_file('myPhotos.xml');
//echo $xml->getName() . "<br />";
foreach ($xml->children() as $child)
{
    echo '<img src="' . $child['src'] . '" alt="gallery image" />';
}
?>

Here is my XML structure:

<slideshow>
<image src="myPhotosResized/image1.jpg" desc="This is the 1st image!" />
<image src="myPhotosResized/image2.jpg" desc="This is the 2nd image!" />
<image src="myPhotosResized/image3.jpg" desc="This is the 3rd image!" />
<image src="myPhotosResized/image4.jpg" desc="This is the 4th image!" />
</slideshow>
Was it helpful?

Solution

Assuming that you want to actually delete the file (and not just remove it from the DOM), either use Ajax or wrap your images with a link that is targeting a script to delete the file:

With Ajax:

 <? 
    $xml = simplexml_load_file('myPhotos.xml');
    //echo $xml->getName() . "<br />";
    foreach ($xml->children() as $child)
    {
        echo '<img src="' . $child['src'] . '" alt="gallery image" onclick="deleteFile('.$child["src"].')" />';
    }
    ?>

<script>
function deleteFile(filename) {
    var t = this;
    $.ajax({
            url: 'deleteFile.php?filename='+filename,
            type: 'post',
            success: function(data) {
              t.style.display = 'none';//hide the link 
              alert('File deleted!');
            }
});
}
</script>    

And on your deleteFile.php you will need to use:

$filename = $_GET['filename'];//gets the file name from the URL
unlink($filename);//deletes the file

Second option:

If you must keep everything with PHP and not use jQuery or Ajax, you can simply wrap the images with a link and set its href to:

echo '<a href="deleteFile.php?filename=' . $child["src"] . '"><img src="' . $child['src'] . '" alt="gallery image" /></a>';   

Hope this helps

OTHER TIPS

The key is to write your HTML properly and then write your jQuery to do the magic

Assuming your HTML is like this, give your elements class names

<img src="' . $child['src'] . '" class="deleteme" alt="gallery image" /><a href="#" class="clicktodelete">Delete me</a>

This jQuery code will do what you want. place it at the end of your file

<script>
    $('.clicktodelete').click(function () {
        $(this).prev('.deleteme').hide();
    });
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top