The PHP file_put_contents () function is the most appropriate choice for writing a string to a file or appending string content at once.
File_put_contents ()
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.
Grammar:
int file_put_contents (string filename, string data [, int flags [, resource context]])
Parameter description:
Parameters |
Description |
FileName |
The file name to write the data to |
Data |
The data to write. The type can be String,array (but not a multidimensional array), or a stream resource |
Flags |
Optional, which specifies how to open/write files. Possible values:
- File_use_include_path: Check the built-in path of the filename copy
- File_append: Writes data appended to the end of the file
- LOCK_EX: Lock the file
|
Context |
Optional, context is a set of options through which you can modify text properties |
Example:
<? PHP Echo file_put_contents ("Test.txt", "This is something.") );? >
To run the example, the browser outputs:
18
The contents of the Test.txt file (in the same directory as the program) are: This is something.
Tips
- If the file does not exist, the file is created, which is equivalent to the fopen () function behavior.
- If the file exists, the contents of the file are emptied by default, and you can set the flags parameter value to File_append to avoid (see below).
- This function can be used safely in binary objects.
Write content in append form
When the flags parameter value is set to File_append, the new data is written in such a way that the content is appended to the contents of the existing file:
<? PHP file_put_contents ("Test.txt", "This is another something.", file_append);? >
After executing the program, the contents of the Test.txt file become: This is something. This is another something.
The behavior of file_put_contents () is actually equal to calling fopen (), fwrite (), and fclose () functions in turn.