我有:
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
但它会覆盖文件的开头。我如何让它插入?
最佳答案
我不完全确定你的问题 - 你是想写入数据而不是覆盖现有文件的开头,还是将新数据写入现有文件的开头,然后保留现有内容是吗?
要在不覆盖文件开头的情况下插入文本,您必须打开它进行追加 ( a+
rather than r+
)
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
如果您尝试写入文件的开头,您必须先读入文件内容(参见 file_get_contents
),然后写入您的新字符串,然后写入文件输出文件的内容。
$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);
上述方法适用于小文件,但您可能会在使用 file_get_conents
尝试读取大文件时遇到内存限制。在这种情况下,请考虑使用 rewind($file)
,它将句柄的文件位置指示符设置为文件流的开头。
注意使用rewind()
时,不要用a
(或a+
)选项打开文件,如:
If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.
关于php - 使用php,如何在不覆盖文本文件开头的情况下插入文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/103593/