Edit row/line in .txt

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
royend
Forum Newbie
Posts: 3
Joined: Thu Sep 29, 2005 12:10 pm

Edit row/line in .txt

Post 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
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

Do your lines have fixed width (in characters)?
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post 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
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post 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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
royend
Forum Newbie
Posts: 3
Joined: Thu Sep 29, 2005 12:10 pm

Post by royend »

Thanks for your reply...
The solution of Pickle works perfectly!

royend :d
Last edited by royend on Thu Sep 29, 2005 4:05 pm, edited 1 time in total.
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post by shiznatix »

my solution did not work :cry: ?
royend
Forum Newbie
Posts: 3
Joined: Thu Sep 29, 2005 12:10 pm

Post 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
Post Reply