Home  >  Article  >  Backend Development  >  How to implement appending and line wrapping using file_put_contents in PHP

How to implement appending and line wrapping using file_put_contents in PHP

墨辰丷
墨辰丷Original
2018-05-24 11:23:312314browse

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:

The role of yield

PHP Namespace (namespace)

##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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn