open file, change content, save file
Posted by hl5 (hl5), 15 September 2005Hello:
I'm trying to open a text file, change some content and then resave it. Instead of getting "newword", the file has "Resource id #3" in it.
Here's the code:
$filename = "c:\\temp\\mydata.txt";
$mystring = fopen($filename, "wb");
$handle = fopen($filename, "wb");
$newstring = str_replace("oldword", "newword", $mystring);
$numbytes = fwrite($handle, $newstring);
print "$numbytes bytes written\n";
But in the file written, mydata.txt, I get "Resource id #3".
Any ideas are much appreciated.
Posted by admin (Graham Ellis), 16 September 2005You need to open your input file with a read attribute. That returns you a file handle through which you read the file with a function such as fread. Then make your changes to the data, re-open the file for write, and write to it.
I've tested that code and it works.
Note that opening a file returns a file handle - you must read from that if you want to access the existing data. Also note that if you're writing back to the same file that you're reading from, you much complete the read before opening the file for write!
Posted by hl5 (hl5), 16 September 2005Mr. Graham:
You da man!
It works well.
Posted by curtis (curtis), 8 October 2005An even easier way would be:
Posted by hl5 (hl5), 8 October 2005curtis:
Posted by curtis (curtis), 8 October 2005Lol, now that I look back at Graham's, my way uses about the same amount of lines any way . Anyway, I guess it doesn't hurt to know different methods to do things
Just in case you might be interested, I'd recommend checking some of these out:
PH: 01144 1225 708225 • FAX: 01144 1225 793803 • EMAIL: email@example.com • WEB: http://www.wellho.net • SKYPE: wellho