我正尝试在php中创建一个简单的程序,该程序读取带有歌曲的文本文件,然后在屏幕上通过每首歌曲旁边的删除按钮将它们打印出来,然后在您单击删除按钮时,歌曲应删除。新文件将写入txt文件,并应在屏幕上刷新。我的代码仅在第二次单击后才能工作。第一次单击实际上确实会修改txt文件,但屏幕上的代码不会刷新。
谢谢
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Music</title>
<body>
<h1>My Music</h1>
<p>My Library</p>
<?php
//read file
$myFile = "test.txt";
//file to array
$lines = file($myFile);
//set array length
$length = count($lines);
//print array on screen with delete button
for ($i = 0; $i < $length; $i++) {
echo $lines[$i] . '<form action="index.php" method="post">
<button type="submit" name="test" value="' . $i . '">Delete</button><br><br></form>';
}
//after clicking delete box remove song from array
if (isset($_POST['test'])) {
//getting song number to remove
$songNumber = $_POST['test'];
//removing song from original array
array_splice($lines, $songNumber, 1);
//open test.txt again
$myFile2 = fopen("test.txt", "w") or die("Unable to open file!");
//set updated array length
$length = count($lines);
//write array to test.txt
for ($i = 0; $i < $length; $i++) {
$txt = $lines[$i];
fwrite($myFile2, $txt);
}
}
?>
</body>
</html>
我正在使用的文本文件
1. turkish march
2. claire de lune
3. symphony no. 9
4. swan lake
5. imperial march
6. helter skelter
答案 0 :(得分:1)
查看代码执行的顺序。首先,它从文件中读取并显示数据。 然后从文件中删除一行。 之后文件已经显示。
只需交换事件顺序:
if (isset($_POST['test'])) {
// perform your delete
}
// Display the contents of the file
$myFile = "test.txt";
// etc.
for ($i = 0; $i < $length; $i++) {
// ...
}
答案 1 :(得分:0)
您正在读取文件,然后删除标题,当您单击按钮时,您会读取未修改的版本,然后对其进行修改,这就是它在第二次刷新时起作用的原因。或单击。更改代码的顺序。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Music</title>
<body>
<h1>My Music</h1>
<p>My Library</p>
<?php
//after clicking delete box remove song from array
// remove file first if needed...
if (isset($_POST['test'])) {
//getting song number to remove
$songNumber = $_POST['test'];
//removing song from original array
array_splice($lines, $songNumber, 1);
//open test.txt again
$myFile2 = fopen("test.txt", "w") or die("Unable to open file!");
//set updated array length
$length = count($lines);
//write array to test.txt
for ($i = 0; $i < $length; $i++) {
$txt = $lines[$i];
fwrite($myFile2, $txt);
}
}
//read file
$myFile = "test.txt";
//file to array
$lines = file($myFile);
//set array length
$length = count($lines);
//print array on screen with delete button
for ($i = 0; $i < $length; $i++) {
echo $lines[$i] . '<form action="index.php" method="post">
<button type="submit" name="test" value="' . $i . '">Delete</button><br><br></form>';
}
?>
</body>
</html>