我有一个歌曲的 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, "$title"<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"] 删除这些歌曲。