drnl10253 2014-01-27 16: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 18: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条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!