0

我有一个歌曲的 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";
?>

而“removesong.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"] 删除这些歌曲。

4

1 回答 1

0

--edit-- 刚刚看到您已经在使用 $_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[]" />
于 2013-10-03T19:55:21.113 回答