|
| HOW TO WRITE TO FILES USING THE fwrite() FUNCTION IN PHP
To write data to file, you use the fwrite() function on PHP. You will need to open the file first in write mode before any writing can take place. It takes two arguments, the file handle and the actual data to write. The data to write can be a string or a variable.
The general format is:
fread(filehandle, data_to_write);
Example 1:
<?
$myFile="test.txt";
$fd=fopen($myFile, "w");
fwrite($fd, "My name is Dan Stern.");
fclose($fd);
?>
Example 2:
<?
$myFile="test.txt";
$data="My friend called today.";
$fd=fopen($myFile, "w");
fwrite($fd, $data);
fclose($fd);
?>
First, we use the fopen function to open the file in write mode. If the file doesn't exist, PHP creates it in the same directory as the fwrite script. Then we use the fwrite function to write the data to file. We then close the file using the fclose function. $contents variable then holds the contents of the file.
Note that fwrite completely erases the file before it writes to it. If you want to add additional data to end of file without erasing the original contents, then use the append mode as follows:
Example
<?
$myFile="test.txt";
$fd=fopen($myFile, "a");
fwrite($fd, "My name is Dan Stern.");
fclose($fd);
?>
 |
|
|