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条)

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题