Training, Open Source computer languages
PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 
Search for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
Python, Lua and Tcl - public course schedule [here]
Private courses on your site - see [here]
Please ask about maintenance training for Perl, PHP, Java, C, C++, Ruby, MySQL and Linux / Tomcat systems
open file, change content, save file

Posted by hl5 (hl5), 15 September 2005

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.


- Harry

Posted by admin (Graham Ellis), 16 September 2005
You 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.


$fname = "demo.txt";
$fhandle = fopen($fname,"r");
$content = fread($fhandle,filesize($fname));

$content = str_replace("oldword", "newword", $content);

$fhandle = fopen($fname,"w");

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 2005
Mr. Graham:

You da man!

It works well.

Many thanks,

- Harry

Posted by curtis (curtis), 8 October 2005
An even easier way would be:

$file = 'path/to/file.txt';
$file_contents = file_get_contents($file);

$fh = fopen($file, "w");
$file_contents = str_replace('foo','bar',$file_contents);
fwrite($fh, $file_contents);

Posted by hl5 (hl5), 8 October 2005


- Harry

Posted by curtis (curtis), 8 October 2005
Lol, 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:

This page is a thread posted to the opentalk forum at and archived here for reference. To jump to the archive index please follow this link.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2018: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01225 708225 • FAX: 01225 793803 • EMAIL: • WEB: • SKYPE: wellho