Writing data is also a common file operation in PHP, where you can use the fwrite () and file_put_contents () functions to write data in a file. The fwrite () function also has an individual named fputs (), whose usage is the same, and the fwrite () function syntax is as follows:
int fwrite (Resource handle,string string[,int length])
The function writes the contents of a string to the file pointer at handle. If length is specified, the write is stopped when it is written to length bytes. If the file content is less than length, all the file contents are output.
The file_put_contents () function is a newly added function of PHP5. The syntax is as follows:
File_put_contents (File,data,mode,context)
Parameter 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_pathFile_appendLock_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. |
return value
The function returns the number of bytes written to the data in the file.
Note: The function of using the file_put_contents () function is the same as calling the fopen (), fwrite (), and fclose () functions at once.
For example:
$filepath = "Test.txt"; $str = " I hate to think of you like this at the moment I am too reconciled with the fragile for the neighbor no soul temperature into ice embarrassed I always alone embrace the whole secret but my friends say I'm too blue to love you I can't say you hug sweet laughing endure overdue sadness if I say I really love you who's going to clean up those broken friendships if I hold this secret warm winter will be far away $fopen =fopen ($filepath, ' WB ') or Die ("file does not exist"); Fwrite ($fopen, $STR); fclose ($fopen); ReadFile ($filepath); file_put_ Contents ($filepath, $STR); ReadFile ($filepath);