我的文本文件包含:
a
b
c
d
e我不知道如何修改我的代码,这样我只能用我在输入框'data‘中输入的任何东西来覆盖第三行(即替换"c")。我的代码如下,目前输入框'data‘的内容完全替换了我的文件:
$data = $_POST['data'];
$file = "data.txt";
$fp = fopen($file, "w") or die("Couldn't open $file for writing");
fwrite($fp, $data) or die("Couldn't write values to file");
fclose($fp);我让它以另一种方式工作,即当页面第一次加载时,下面的代码只在文本框中读取第3行:
$file = "data.txt";
$lines = file( $file );
echo stripslashes($lines[2]);有没有人能建议我需要用来实现这个目标的代码?
发布于 2012-10-30 20:08:36
唯一的方法是读取整个文件,更改第三行,然后将其全部写回。基本上,就像这样:
$lines = file($file);
$lines[2] = $_POST['data'];
file_put_contents($file, implode("\n", $lines));顺便说一句,你的阅读代码并不“只”读取第3行--它按照file()读取所有行,然后你只读取第3行。
https://stackoverflow.com/questions/13138526
复制相似问题