我正在编写简单的调试脚本,它允许我(当按下保存按钮时)向.txt
文件添加新行,然后在页面加载时获取上次保存的任何内容。
例如,我有我的user_input.txt
文件,当我按保存时 - 我正在向该文件添加时间戳和 textarea 内容。当页面再次加载时,我从上次保存中获取内容。
目前我有这个获取代码:
$current_user_input = file_get_contents('user_input.txt');
if($current_user_input === false) {
$current_user_input = '';
}
并设置:
if($_POST) {
if($_POST['user_input']) {
$file = 'user_input.txt';
file_put_contents($file, $_POST['user_input']);
}
}
显然目前它只是覆盖文本文件并获取其所有内容,我如何修改它以使其执行我上面描述的操作?
为了保存,您需要附加数据(正如 AjAX 的评论所说的 using FILE_APPEND
),但还要添加行尾以确保它们出现在单独的行上。
if($_POST) {
if($_POST['user_input']) {
$file = 'user_input.txt';
file_put_contents($file, $_POST['user_input'].PHP_EOL, FILE_APPEND);
}
}
然后,您可以使用file()
which 将文件逐行读取到数组中并获取最后一个元素来检索最后一行...
$oldInput = file($file);
if(!empty($oldInput)) {
$current_user_input = array_pop($oldInput);
}
else {
$current_user_input = '';
}
更新:对于多行内容,您可以将新行更改为<br />
标签...
file_put_contents($file,
str_replace( PHP_EOL, '<br />', $_POST['user_input']).PHP_EOL,
FILE_APPEND);
这会将所有内容保留在一行中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句