php - 使用php,如何在不覆盖文本文件开头的情况下插入文本

标签 php insert

我有:

<?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/

相关文章:

mysql - 更新否则插入 MySQL 查询

php - 产品统计

php - 在单元测试中模拟被测试的对象是不是很糟糕?

php - MySQLi 无法准备语句

python - 用于插入 Google Fusion Tables 的 Python 中经过身份验证的 POST

insert - 使用 Sublime Text 在覆盖/插入模式下粘贴

php imap foward/redirect 帐户获取原始地址(送达)

php - 将 html(填充 mysql)表导出到 excel 文件

javascript - mysql 查询返回 false,mysql 插入有效但回显语句不显示

oracle: INSERT 其中 a=b