Page 1 of 1

Editing a text file using PHP

Posted: Tue Aug 29, 2006 10:50 pm
by cursed
How would you find a line on a text file using php, then editing it?
I looked at the manual, and I tried some code, but it didnt work.

Posted: Wed Aug 30, 2006 12:08 am
by shiznatix
use the function file() to make an array of the file you want then take the line number you want to edit and edit it. then you can save it with fwrite() and whatnot.

Posted: Wed Aug 30, 2006 12:14 am
by cursed
is it possible not to use the line number? some replace function?

Posted: Wed Aug 30, 2006 12:49 am
by RobertGonzalez
You can loop through the array made by file() and search and replace as needed.

Posted: Wed Aug 30, 2006 7:45 am
by s.dot
You can also get the entire contents into a single string, ready for replacing.. by using file_get_contents()

Posted: Wed Aug 30, 2006 8:08 pm
by cursed
i tried scottayy's way, but it didnt work.

can someone post a short code snippet? :oops:

Posted: Thu Aug 31, 2006 12:04 am
by RobertGonzalez
Tell you what, post what you have and let us help you, instead of us doing it for you.

Posted: Thu Aug 31, 2006 5:42 pm
by cursed
never mind, i got it to work. Thanks for the help anyways. :D

Posted: Thu Aug 31, 2006 5:45 pm
by s.dot
Well for other people reading the topic who may be curious..

If you're just looking to replace some text in a file, something like the following would work.

Code: Select all

$file = file_get_contents('somefile.txt');
$file = str_replace('data you\'re looking for', 'data to replace it', $file);

$handle = fopen($file, "w");
fwrite($handle,$file);
fclose($handle);
This snippet made use of str_replace(), but much more advanced replacing like preg_replace() could've been coded.