【发布时间】:2012-11-09 19:45:15
【问题描述】:
我有一个文本文件,将 lastname, first name, address, state, etc 存储为带有 | 分隔符的字符串,并且每条记录位于单独的行中。
我需要将每条记录存储在新行上并且工作正常的部分;但是,现在我需要能够返回并更新特定行上的名称或地址,但我无法让它工作。
这个how to replace a particular line in a text file using php? 在这里帮助了我,但我还没有到那里。这会覆盖整个文件,我会丢失记录。任何帮助表示赞赏!
经过一些编辑似乎现在可以工作了。我正在调试,看看有没有错误。
$string= implode('|',$contact);
$reading = fopen('contacts.txt', 'r');
$writing = fopen('contacts.tmp', 'w');
$replaced = false;
while (!feof($reading)) {
$line = fgets($reading);
if(stripos($line, $lname) !== FALSE) {
if(stripos($line, $fname) !== FALSE) {
$line = "$string";
$replaced = true;
}
}
fwrite($writing, "$line");
//fputs($writing, $line);
}
fclose($reading); fclose($writing);
// might as well not overwrite the file if we didn't replace anything
if ($replaced)
{
rename('contacts.tmp', 'contacts.txt');
} else {
unlink('contacts.tmp');
}
【问题讨论】:
-
您能否解释一下您所说的
this overwrites the whole file的确切含义。所有的行都变成同一个记录吗? -
整个文件 contacts.txt 变为空白。我有一个单独的脚本来添加条目,所以我先在那里放几行进行测试。当我运行此代码时,它会删除文件中的所有内容。此外,我更喜欢在不将整个文件转储到可能的数组中的情况下完成此操作,以防将来文件变得太大。尝试使用更少的内存使其工作。谢谢。
-
contacts.txt不可能为空,它以只读模式打开。你的意思是contacts.tmp?
标签: php file replace line fwrite