drnl10253 2014-01-27 08:41
浏览 91
已采纳

PHP - 删除选定了特定属性的子项

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>
  • 写回答

2条回答 默认 最新

  • douyi1982 2014-01-27 10:00
    关注

    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

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部