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

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀