PHP - 根据选定的Checkbox Array值删除XML标记元素

时间:2013-10-03 19:49:54

标签: php xml

我有一个歌曲的XML文件,我正在使用PHP构建一个表单(带有复选框)来删除该文件中的一首或多首歌曲。我遇到的问题是我无法弄清楚如何遍历表单中的ID列表并删除带有这些ID的歌曲。

这是我的XML:

<?xml version="1.0" encoding="utf-8"?>
<songs>
    <song id="1380682359">
        <artist>Artist</artist>
        <title>Title</title>
    </song>
    <song id="1380682374">
        <artist>Artist</artist>
        <title>Title</title>
    </song>
    <song id="1380828782">
        <artist>Artist</artist>
        <title>Title</title>
    </song>
</songs>

这构建了表单:

<?
echo "<form action='removesong.php' method='post'>\n";
$doc = new DOMDocument();
$doc->load('songlist.xml');
$songlist = $doc->getElementsByTagName("song");
foreach($songlist as $song) {
    $id = $song->getAttribute("id");
    $artists = $song->getElementsByTagName("artist");
    $artist = $artists->item(0)->nodeValue;
    $titles = $song->getElementsByTagName("title");
    $title = $titles->item(0)->nodeValue;
    echo "<input type='checkbox' name='SongsToRemove[]' value='" . $id . "'> $artist, &quot;$title&quot;<br>\n";
}
echo "<br><input type='submit' value='Delete Song' />\n</form>\n";
?>

而且“removong.php”将会接近这一点(我认为):

<?
$doc = new DOMDocument();
$doc->load("songlist.xml");
$songs = $doc->getElementsByTagName("song");
foreach($songs as $song) {
    if($song['id'] == $_POST["SongsToRemove"]) {
        unset($song); // or $song->removeChild($song);
    }
}
$doc->save("songlist.xml");
?>

我无法弄清楚如何使用$ _POST [“SongsToRemove”]来删除这些歌曲。

1 个答案:

答案 0 :(得分:0)

- 编辑 - 只是看到你已经在使用$ _POST数组,所以修改了示例:

试试这个:

<?
// post variable is string with comma seperators
//$_POST['SongsToRemove'] = '1380682359,1380828782';
//$songs_to_remove = explode( ',', $_POST['SongsToRemove'] );

// songs to remove is already post array:
$songs_to_remove = $_POST['SongsToRemove'];

$doc = new DOMDocument();
$doc->load("songlist.xml");
$songs = $doc->getElementsByTagName("song");
foreach($songs as $song) {
    if( in_array( $song['id'], $songs_to_remove ) {
        unset($song); // or $song->removeChild($song);
    }
}
$doc->save("songlist.xml");
?>

您可以尝试的其他事情是将歌曲设置为删除到数组(您也可以使用HTML执行此操作):这将消除爆炸等的需要......

<input type="text" name="SongsToRemove[]" />
<input type="text" name="SongsToRemove[]" />
<input type="text" name="SongsToRemove[]" />