Two PHP functions can save a string to a file, the format of the fwrite () function is:
int fwrite (resource handle, string string [, int length])
It can only write strings .
The format of the file_put_contents () function is:
int file_put_contents (string $filename, mixed $data [, int $flags [, Resource $context]])
Where file is the path to the document, data can be a string, can be a one-dimensional array or a two-dimensional array, not a multidimensional array
Both methods automatically create files when the file to be written does not exist. When the file exists, use the fopen () function to open the file resource mode before using the fwrite () function, or use the third parameter of the file_put_contents () function to determine the mode to write to the file:
For example
When using fopen (), fwrite (), fclose (), this series of functions
<? PHP $filename = "Data.txt"; $handle fopen ($filenamedie ("open". ) $filename. " File failed "); $str = "Updating your profile with your name"; fwrite ($handle,$str); fclose ($handle);
is equivalent to the file_put_contents ()
<? PHP $filename = "Data.txt"; $str = "Updating your profile with your name"; file_put_contents ($filename,$str);
Simplified to 1 lines where 3 lines of code were originally needed.
fopen (), fwrite (), fclose () when additional write files are required.
<? PHP $filename = "Data.txt"; $handle fopen ($filenamedie ("open". ) $filename. " File failed "); $str = "Updating your profile with your name"; fwrite ($handle,$str); fclose ($handle);
is equivalent to the file_put_contents ()
<? PHP $filename = "Data.txt"; $str = "Updating your profile with your name"; file_put_contents ($filename,$str, file_append);
In addition, in order to avoid multiple simultaneous operation of files, you can increase the file lock declaration:
file_put_contents ($filename,$str, file_append| LOCK_EX);
efficiency: Thefile_put_contents () function is the same as calling fopen (), fwrite (), and fclose ( ) in turn, that is, File_put_contents () is written to each piece of data To open and close resources, while using fopen (), fwrite (), fclose (), you only need to open resources once and shut down resources once, efficiently using fopen (), fwrite (), fclose () faster, and for processing large amounts of data If the amount of data processed is not much, the file_put_contents () function can be used for brevity.
Comparison of PHP fwrite () function with file_put_contents () function