The file_put_contents () function is used to write a string to a file, successfully returning the number of bytes written to the data in the file, and FALSE if the failure is unsuccessful.
Instructions for use:
File_put_contents (File,data,mode,context)
Parameter description:
file name of file to write data to
Data to be written to. The type can be String,array (but not a multidimensional array), or a stream resource
Mode is optional, which specifies how to open/write files. Possible values:
1.file_use_include_path: Check the built-in path of the filename copy
2.file_append: Writes data appended to the end of the file
3.LOCK_EX: Lock the file
Parameters |
Description |
File |
Necessary. Specifies the file to write the data to. If the file does not exist, a new file is created. |
Data |
Optional. Specifies the data to write to the file. Can be a string, an array, or a data stream. |
Mode |
Optional. Specifies how to open/write files. Possible values:
- File_use_include_path
- File_append
- Lock_ex
|
Context |
Optional. Specifies the environment for file handles. The context is a set of options that modify the behavior of the stream. If NULL is used, it is ignored. |
Context is optional, and context is a set of options through which you can modify text properties
Example:
<?php
echo file_put_contents (" Test.txt "," This is Test.txt ");
?>
Run the example, browser output: Word a length
While the Test.txt file (in the same directory as the program) is: this is test.txt
Tips
? If the file does not exist, create a file that is equivalent to the fopen () function behavior.
? If the file exists, the contents of the file will be emptied by default, and you can set the flags parameter value to File_append to avoid (see below).
? This function can be used safely with binary objects.
Append to file contents
<?php
File_put_contents ("Test.txt", "My Add Contents", file_append);
?>
After executing the program, the contents of the Test.txt file become: This istest.txt My Add contents
Note: The behavior of file_put_contents () is actually equal to calling fopen (), fwrite (), and fclose () functions in turn.
PHP string to write to file or to join file (file_put_contents)