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
Edit row/line in .txt
Moderator: General Moderators
- shiznatix
- DevNet Master
- Posts: 2745
- Joined: Tue Dec 28, 2004 5:57 pm
- Location: Tallinn, Estonia
- Contact:
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);Or something like:
UNTESTED
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.
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');
}Real programmers don't comment their code. If it was hard to write, it should be hard to understand.