PHP Write File
The PHP fwrite()
function is used to write data to a file. It returns the number of bytes written or false
on failure.
Syntax
The syntax for fwrite()
is:
fwrite(file, string, length)
Parameters:
file
(Required): Specifies the file to write tostring
(Required): Specifies the string to writelength
(Optional): Specifies the number of bytes to write. Default is the length of the string.
Example
In this example, we will create a new file called "newfile.txt" and write the text "Hello World" to it.
$file = fopen("newfile.txt", "w");
$string = "Hello World";
fwrite($file, $string);
fclose($file);
Output
The output of the code above will be a new file called "newfile.txt" that contains the text "Hello World".
Explanation
We first open the file with the fopen()
function using the "w" mode to open it for writing. We then specify the string we want to write using the $string
variable, and use the fwrite()
function to write it to the file. Finally, we close the file using fclose()
.
Use
The fwrite()
function is useful for writing to files in PHP. It can be used to write text data, binary data, and other types of data to a file.
Important Points
- The
fwrite()
function overwrites any existing data in the file. - If the file does not exist, it will be created.
- The
fwrite()
function can write data to binary files as well as text files.
Summary
The fwrite()
function is used in PHP to write data to a file. It takes the file handle, the data to write, and an optional length of data to write as parameters. It returns the number of bytes written or false
on failure.