PHP file writing
Posted by tutor | Posted in PHP Tutorial | Posted on 09-08-2010-05-2008
0
fwrite() Function
PHP can be used to write to a file. The fwrite() function allows data to be written to any type of file. It takes two parameters, first parameter is the file handle and its second parameter is the string of data that is to be written.
A file handle is the variable which stores the pointer, which points the start of a file which is being opened for writting by the fopen function.
$sampleFile = “sample.txt”;
$samplefile_handle = fopen($sampleFile, ‘w’) or die(“File opening failed”);
$data = “PHP is good\n”;
fwrite($samplefile_handle, $data);
$data = “PHP is not good\n”;
fwrite($samplefile_handle, $data);
fclose($samplefile_handle);
The $samplefile_handle variable contains the file handle for testFile.txt.
We wrote to the file sample.txt twice. Each time we wrote to the file we sent the string $stringData that first contained “PHP is good” and second contained “PHP is not good”. After we finished writing we closed the file using the fclose function.
If you were to open the testFile.txt file it would look like this:
Contents of the testFile.txt File:
- PHP is good
PHP is not good
PHP – File Write: Overwriting
Now let’s see what happens when you open an existing file for writing.
The data contained in the file is cleared and the file becomes empty.
$sampleFile = “sample.txt”;
$samplefile_handle = fopen($sampleFile, ‘w’) or die(“File opening failed”);
$data = “I am good\n”;
fwrite($samplefile_handle, $data);
$data = “I am tutor\n”;
fwrite($samplefile_handle, $data);
fclose($samplefile_handle);
If you now open the sample.txt file you will see that the previous data is vanished, and only the currentl written data is present.
Contents of the sample.txt File:
- I am good
I am tutor
