Category Archives: PHP – File Write: fwrite Function

PHP – File Write: fwrite Function

We can use php to write to a text file. The fwrite function allows data to be written to any type of file. Fwrite’s first parameter is the file handle and its second parameter is the string of data that is to be written. Just give the function those two bits of information and you’re good to go!
Below we are writing a couple of names into our test file filename and separating them with a carriaged return.
PHP Code:

$myFile = "filename.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "phpfresher";
fwrite($fh, $stringData);
fclose($fh);

The $fh variable contains the file handle for filename.txt. The file handle knows the current file pointer, which for writing, starts out at the beginning of the file.
We wrote to the file filename.txt twice. Each time we wrote to the file we sent the string $stringData that first contained mahohar khatri and second contained saroj karki. After we finished writing we closed the file using the fclose function.
If you were to open the filename.txt file in NOTEPAD it would look like this:
phpfresher