This article mainly introduces the method of appending and wrapping file_put_contents in PHP. Interested friends can refer to it. I hope it will be helpful to everyone.
In some applications of PHP, it is necessary to write logs or record some information, in this case. You can use fopen(), fwrite() and fclose() to operate. You can also simply use file_get_contents() and file_put_contents().
file_put_contents() to write files. The default is to rewrite the file, which means the original content will be replaced. To append, use the parameter FILE_APPEND.
Write content in append form. When the flags parameter value is set to FILE_APPEND, it means writing new data by appending content after the existing file content:
FILE_APPEND:Write data by appending to the end of the file
int file_put_contents ( string filename, string data [, int flags [, resource context]] ) file_put_contents("log.txt", "Hello world everyone.", FILE_APPEND);
//Parameter description:
filename //The name of the file to be written
data //The data to be written. The type can be string, array (but not multi-dimensional array), or stream resource
#flags //Optional, specifies how to open/write the file. Possible values:
FILE_USE_INCLUDE_PATH: // Check the built-in path for a copy of filename
FILE_APPEND: // Write data appended to the end of the file
LOCK_EX: //Lock the file
context //Optional, Context is a set of options through which text attributes can be modified
Many times the log needs to be wrapped. It is not recommended to use \r\n because:
In windows \r\n is a newline
In Mac \r is a newline
In Liunx\n is a newline
But PHP provides a constant to match different operating systems, namely:
PHP_EOL
file_put_contents("log.txt", "Hello world everyone.".PHP_EOL, FILE_APPEND);
The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
##PHPGet the image width and height, size, image type, img attribute used for layout
The above is the detailed content of How to implement appending and line wrapping using file_put_contents in PHP. For more information, please follow other related articles on the PHP Chinese website!