Writing data in a file is another common feature of file handling. In PHP, there are various modes that facilitates different ways and features of writing data into a file, including: w, r+, w+, x, x+, c or c+ mode. PHP also supports some functions to write to a file.
PHP Write File functions are:
- PHP fwrite()
- PHP fputs()
PHP fwrite() function:
To write a file in PHP, fwrite() function is used.
Syntax:
int fwrite ( resource $filename , string $string )
- Filename: This parameter represents the name of the file to write to.
- String: This parameter represents the string to be written.
Example:
<!DOCTYPE html> <html> <body> <?php $samplefile = fopen("phpfile.txt", "w"); fwrite($samplefile, "Hello PHP!"); $samplefile = fopen("phpfile.txt", "r"); echo fread($samplefile, filesize("phpfile.txt")); fclose($samplefile); ?> </body> </html> |
Output
Hello PHP! |