The file_put_contents() writes a string to a file.
PHP file_put_contents() Function has the following syntax.
file_put_contents(file,data,mode,context)
Parameter | Is Required | Description |
---|---|---|
file | Required. | File to write. For non-existing file, this function will create one |
data | Required. | Data to write. Can be a string, an array or a data stream |
mode | Optional. | How to open/write to the file. |
context | Optional. | Context of the file handle. |
Possible values for mode:
This function returns the number of bytes that were written to the file, or FALSE on failure.
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.
Use the === operator for testing the return value of this function.
file_put_contents() and fwrite() complement functions file_get_contents() and fread(), respectively.
<?PHP//from ww w .java 2s .c o m
echo file_put_contents("test.txt","Hello World. Testing!");
$myarray[] = "This is line one";
$myarray[] = "This is line two";
$myarray[] = "java2s.com";
$mystring = implode("\n", $myarray);
$filename = "test.txt";
$numbytes = file_put_contents($filename, $mystring);
print "$numbytes bytes written\n";
?>
The third parameter to file_put_contents() can be set to FILE_APPEND, If you do not use FILE_APPEND, the existing text will be replaced.
Use FILE_APPEND to avoid deleting the existing content of the file.
The code above generates the following result.