0

I have a text file that stores lastname, first name, address, state, etc as a string with a | 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? 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');
}   
Community
  • 1
  • 1
user1781482
  • 623
  • 3
  • 15
  • 24
  • 1
    Could you please explain what exactly you mean when you say `this overwrites the whole file`. Do all of the lines become the same record? – Asad Saeeduddin Nov 09 '12 at 19:51
  • The whole file contacts.txt becomes blank. I have a separate script that adds the entries so I put few lines on there first for testing. When I run this code it erases everything in the file. Also I prefer to get this done without dumping the whole file in an array of possible, in case the file becomes too big in the future.Trying to make it work with using less memory. Thanks. – user1781482 Nov 09 '12 at 20:00
  • `contacts.txt` cannot possibly become blank, it is opened in readonly mode. Did you mean `contacts.tmp`? – Asad Saeeduddin Nov 09 '12 at 20:14

1 Answers1

2

It seems that you have a file in csv-format. PHP can handle this with 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

$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. Just open the file in Append-mode http://de3.php.net/manual/en/function.fopen.php :

$writing = fopen('contacts.tmp', 'a');
Varon
  • 3,736
  • 21
  • 21