我有两个网页 a.php 和 b.php。 texboxes 中提交的值将写入文本文件。
a.php :
<html>
<?php
if (isset($_POST['Submit1'])) {
$aa = $_POST['alpha'];
$f = fopen("text.txt", "w");
fwrite($f,$aa."\n");
}
else
{
$f= fopen("text.txt",'r');
while ((!feof($f)) && ($found == 0)) {
list($aa)=fscanf($f,"%f[^\n]");
}
}
fclose($f);
?>
<form action="a.php" name="Calculation" method="post">
Alphabet: <INPUT TYPE ="TEXT" id="alph" Name "alpha" VALUE="<?PHP print $aa; ?>">
<Input Type = "Submit" Name = "Submit1" Value ="Save Parameters">
</form>
</html>
而 b.php 是:
<!DOCTYPE html>
<html>
<?php
if (isset($_POST['Submit1'])) {
$bb = $_POST['beta'];
file_put_contents("text.txt", $bb."\n" , FILE_APPEND);
}
else
{
$f= fopen("text.txt",'r');
while ((!feof($f)) && ($found == 0)) {
list($aa)=fscanf($f,"%f[^\n]");
list($bb)=fscanf($f,"%f");
}
}
fclose($f);
?>
<form action="b.php" name="Calculation" method="post">
Alphabet: <INPUT TYPE ="TEXT" id="betaa" Name ="beta" size="5" VALUE="<?PHP print $bb; ?>">
<Input Type = "Submit" Name = "Submit1" Value ="Save Parameters">
</form>
</html>
代码工作正常,如果我在 a.php 文本框中输入第一个值,在 b.php 文本框中输入第二个值,文本框中的值将写入文本文件。例如,如果我将 aa 放在 a.php 的文本框中,将 bb 放在 b.php 的文本框中,我将得到 p>
啊啊 bb
在我的文本文件中。但是,如果我返回到我的 a.php 文件并在其文本框中输入一个新值,我将丢失 bb。有没有办法只更改文本框第一行的值并将 bb 保留在文本框的第二行? .问题是,如果我添加一个新值,我将丢失我的 b.php 脚本的值。我不想增加文本文件中的行数。我想知道是否有办法用 cc 重写 aa。
最佳答案
您正在覆盖 a.php
中的文件使用 w
开关。
使用 a
切换到追加。
$f = fopen("text.txt", "a");
查阅手册:
或者,像在另一个文件 (b.php) 中那样使用 file_put_contents()
file_put_contents("text.txt", $bb."\n" , FILE_APPEND);
^^^^^^^^^^^
它做同样的事情。
编辑:
"I have a webpage that has several text boxes that need to be filled and the values are saved in a text file when the submit button is hit. Then there is another webpage that has several text boxes as well that need to be filled out and the values will have to be added to the same text file.
So if the user after pressing the submit button decides to change a value of one text box in a.php and then hit submit again I will lose all the information in bb.php unless I add more lines to my text file with the new information."
另一种方法是使用两个单独且不同的文件名,同时保留您现在拥有的文件名。
这里是一个例子,连接文件:
<?php
$file1 = file_get_contents('file1.txt');
$file2 = file_get_contents('file2.txt');
$show_all = $file1 . $file2;
echo $show_all;
- 我用了
file_get_contents()
在此示例中,因为我不知道您目前如何显示网页中的内容。
旁注:
如果要在两者之间添加换行符,请使用 <br>
.
$show_all = $file1 . "<br>" . $file2;
或者只是一个简单的空格:
$show_all = $file1 . " " . $file2;
关于php - 用php修改一个文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30084833/