Page 1 of 1

Edit row/line in .txt

Posted: Thu Sep 29, 2005 12:18 pm
by royend
Hi.
I have a .txt document full of data, all sorted like:
| ID | first_name | last_name | data | more_data \n

I add and delete lines inn the file, but I do not know how I may edit one perticular line and save it at the same place after. It is important that I may save it at the same rownumber in the file.

ie: My file has 7 rows of data. I want to edit row 4. After editting I need to save the edited line to row 4, and thereby replace the originale line.

Does anyone here have any ideas?
Looking forward to your replies...
royend

Posted: Thu Sep 29, 2005 12:29 pm
by Weirdan
Do your lines have fixed width (in characters)?

Posted: Thu Sep 29, 2005 12:31 pm
by shiznatix

Code: Select all

$open = file_get_contents('text.txt');
$go = explode("\n", $open);

for ($i=0; $i<count($go); $i++)
{
  if ($i == 3)
    //it is the 4th line!!! EDIT YOUR SHIZNAT!
}

$ddd = fopen('text.txt', 'w');
fwrite($ddd, $new_contents);
that should work

Posted: Thu Sep 29, 2005 12:49 pm
by pickle
Or something like:

UNTESTED

Code: Select all

$file_contents = file('/test/file.txt');
$file_contents[3] = "edited line contents";

$fh = fopen('/test/file.txt','w');
foreach($file_contents as $line)
{
  fwrite($fh,$line.'\n');
}
I personally like this better because I get nervous relying on parsing to put myself on the correct line. Nothing technically wrong with it though.

Posted: Thu Sep 29, 2005 3:39 pm
by royend
Thanks for your reply...
The solution of Pickle works perfectly!

royend :d

Posted: Thu Sep 29, 2005 4:04 pm
by shiznatix
my solution did not work :cry: ?

Posted: Thu Sep 29, 2005 4:17 pm
by royend
Well, I guess it worked, but it left me in the open on my real issue: How to save my edited line at the same row int txt-file as my original line was.
Thanks to both of you...
royend