PHP file processing writes data to files is also a common file operation in PHP. in PHP, you can use the fwrite () and file_put_contents () functions to write data to files. The fwrite () function is also called fputs () in the same usage. the syntax of the fwrite () function is as follows:
Int fwrite (resource handle, string [, int length])
This function writes the content string to the file pointer handle. If the length is specified, when the length is written, the write will stop. If the file content length is less than length, all the file content will be output.
The file_put_contents () function is a newly added function of PHP5. Syntax:
file_put_contents(file,data,mode,context)
Parameter description
| File |
Required. Specifies the file to write data. If the file does not exist, create a new file. |
| Data |
Optional. Specifies the data to be written into the file. It can be a string, array, or data stream. |
| Mode |
Optional. Specifies how to open/write files. Possible values:
FILE_USE_INCLUDE_PATH
FILE_APPEND
LOCK_EX |
| Context |
Optional. Specifies the file handle environment.
Context is a set of options that can modify the behavior of a stream. If null is used, this parameter is ignored. |
Return value
This function returns the number of bytes written to the file.
Note: Using the file_put_contents () function is the same as calling the fopen (), fwrite (), and fclose () functions at one time.
For example:
$ Filepath = "test.txt "; $ str = "I hate to think this way. you don't care about yourself. at this moment, I am too willing to be weak. my neighbor has no soul. it turns ice into ice. I always hold the whole secret alone, but my friends say that I am too much. melancholy, love you, I can't say that you're embracing sweetness, talking and laughing, and enduring the grief of the deadline. if I say that I really love you, who will clean up the broken friendship? if I hold on this secret, the warmth of the winter will be far away. "; $ fopen = fopen ($ filepath, 'WB ') or die ("The file does not exist"); fwrite ($ fopen, $ str); fclose ($ fopen ); readfile ($ filepath); file_put_contents ($ filepath, $ str); readfile ($ filepath );