【问题标题】:Replace a particular line in a text file using php?使用php替换文本文件中的特定行?
【发布时间】: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


【解决方案1】:

您似乎有一个 csv 格式的文件。 PHP 可以使用 fgetcsv() http://php.net/manual/de/function.fgetcsv.php

处理这个问题
if (($handle = fopen("contacts.txt", "r")) !== FALSE) {
    $data = fgetcsv($handle, 1000, '|')
    /* manipulate $data array here */
}

fclose($handle);

所以你得到了一个你可以操作的数组。在此之后,您可以使用 fputcsv http://www.php.net/manual/de/function.fputcsv.php 保存文件

$fp = fopen('contacts.tmp', 'w');

foreach ($data as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);

好吧,在阿萨德的评论之后,还有另一个简单的答案。只需在 Append-mode http://de3.php.net/manual/en/function.fopen.php 中打开文件即可:

$writing = fopen('contacts.tmp', 'a');

【讨论】:

  • 但这与他的问题无关。
  • 你是对的,但我希望我没有想太多。我为实际问题的解决方案添加了附加信息。
猜你喜欢
  • 2011-03-01
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多