Home  >  Article  >  Backend Development  >  How to implement file_put_contents appending and line wrapping in php?

How to implement file_put_contents appending and line wrapping in php?

PHPz
PHPzOriginal
2017-04-03 18:20:112586browse

The following editor will bring you an article on how to implement file_put_contentsappend and line break in PHP. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.

In some PHP applications, you need 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 //To write Data file name

data //The data to be written. The type can be string, array (but not multidimensional array), or stream resource

flags //Optional, specifies how to open/write Import the file. Possible values:

FILE_USE_INCLUDE_PATH: // Check the built-in path for a copy of filename

FILE_APPEND:// // Appended at the end of the file Method to write data

LOCK_EX: //Lock the file

context //Optional, Context is a set of options through which the text can be modified Properties

#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 implementation method of file_put_contents appending and line wrapping in PHP is all the content shared by the editor. I hope it can give you a reference, and I hope everyone will support Script House.

The above is the detailed content of How to implement file_put_contents appending and line wrapping 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