简体   繁体   English

使用php替换文本文件中的特定行?

[英]Replace a particular line in a text file using php?

I have a text file that stores lastname, first name, address, state, etc as a string with a | 我有一个文本文件,它将lastname, first name, address, state, etc为带有|的字符串 delimiter and each record on a separate line. 分隔符和单独行上的每条记录。

I have the part where I need to store each record on a new line and its working fine; 我有一个部分,我需要将每条记录存储在一个新的行上,并且它的工作正常; however, now I need to be able to go back and update the name or address on a particular line and I can't get it to work. 但是,现在我需要能够返回并更新特定行上的名称或地址,我无法让它工作。

This how to replace a particular line in a text file using php? 这个如何使用php替换文本文件中的特定行? helped me here but I am not quite there yet. 在这里帮助了我,但我还没到那儿。 This overwrites the whole file and I lose the records. 这会覆盖整个文件而丢失记录。 Any help is appreciated! 任何帮助表示赞赏!

After some edit seems to be working now. 经过一些编辑似乎现在正在运作。 I am debugging to see if any errors. 我正在调试以查看是否有任何错误。

$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');
}   

It seems that you have a file in csv-format. 看来你有一个csv格式的文件。 PHP can handle this with fgetcsv() http://php.net/manual/de/function.fgetcsv.php 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);

So you get an array that you can manipulate. 所以你得到一个可以操作的数组。 After this you can save the file with fputcsv http://www.php.net/manual/de/function.fputcsv.php 在此之后,您可以使用fputcsv http://www.php.net/manual/de/function.fputcsv.php保存文件

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

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

fclose($fp);

Well, after the comment by Asad, there is another simple answer. 那么,在Asad的评论之后,还有另一个简单的答案。 Just open the file in Append-mode http://de3.php.net/manual/en/function.fopen.php : 只需在附加模式http://de3.php.net/manual/en/function.fopen.php中打开文件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM