update text file

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
duk
Forum Contributor
Posts: 199
Joined: Wed May 19, 2004 8:45 am
Location: London

update text file

Post by duk »

hy

if i read a file with 500 lines, and if i want to replace text at the line 200 how can i do this ??? using fwrite()

thanks in advance
User avatar
SomeOne
Forum Commoner
Posts: 27
Joined: Tue Jul 25, 2006 2:06 am

Post by SomeOne »

Code: Select all

function replace_my_line($line, $new)
{
$line = 200; //if you define number of line with function call comment this line!
$file = "yourfile.txt";
$a = file("$file"); //first load txt file inty array
$new // holds your new text for line 200
$a[$line] = $new //replace the line 200 with your new content
$a = implode("", $a) //make a writable string (you cannot write array into txt file)

$handleTXT = fopen($file, "w");//open TXT file
fwrite($handleTXT, $a); //write the content to txt file
fclose($handleTXT); // close txt file...
}
you can call this function by;

Code: Select all

replace_my_line($line, $new);
//$new is NEW content of a line
//$line is number of line in txt file
i write it on the fly so sorry if there are some bugs..
this should work
duk
Forum Contributor
Posts: 199
Joined: Wed May 19, 2004 8:45 am
Location: London

Post by duk »

humm the ideia is put the file in the array and then write everything into it again...

the only problem i see is if anything make the cpu stop i will loose all information untill the line he wrote...

but anyway nice, well spoted :D
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

duk wrote:the only problem i see is if anything make the cpu stop i will loose all information untill the line he wrote...
Is that likely to happen? If it does is it your problem?
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Post Reply