Home>Article>Backend Development> Can php modify file content?

Can php modify file content?

青灯夜游
青灯夜游 Original
2021-10-12 12:46:42 3429browse

php can modify the file content. Method: 1. Use the fopen() function to open the file, and use the fwrite() function to write data in the opened file to modify the file. 2. Directly use the file_put_contents() function to modify the file by clearing the file and adding data again or by adding data at the end of the file.

Can php modify file content?

The operating environment of this tutorial: windows7 system, PHP version 7.1, DELL G3 computer

php can modify the file content. Here are several methods to introduce to you.

1. Use the fwrite() function

fwrite($handle, $string, $length)The function can write a string into the file. The fwrite() function can write the contents of $string to the file pointer $handle. If $length is specified, writing will stop when $length bytes have been written or $string has been written. If the function is successfully executed, the number of bytes written will be returned. If the function fails, FALSE will be returned.

Example 1: Clear the file and re-add data

Example 2: Add data at the end of the file

2. Use the file_put_contents() function

file_put_contents($filename,$data,$mode,$context)The function can write a string to a file and accepts two required parameters $filename (the file to be opened) and $data (the content to be inserted, which can be a string, one-dimensional array or resource type), two omissible parameters $mode and $context (the environment of the file handle).

Among them, the $mode parameter is used for how to open/write files (i.e. file mode). It has three values:

  • ##FILE_USE_INCLUDE_PATH: Default value, used to overwrite the original There is data.

  • FILE_APPEND: If file $filename already exists, append data instead of overwriting.

  • LOCK_EX: Obtain an exclusive lock while writing.

Example 1: Clear the file and re-add data

Example 2: Add data at the end of the file

Recommended learning: "

PHP Video tutorial

The above is the detailed content of Can php modify file content?. 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