Home > Article > Backend Development > How to add data at the end of the file in php file operation
At the end of the previous article "php file operation: How to clear the file and re-add data" we introduced a method to add data (that is, append data) at the end of the file--file_put_contents() . The following article will introduce you to another method of adding data at the end of the file. You can refer to it if necessary.
Let’s get straight to the point! We have a text file named "test.txt", the content of which is:
We want to add the following piece of data at the end of the file:
https://www.php.cn/
Let’s take a look at the implementation code:
<?php header("Content-Type: text/html;charset=utf-8"); //设置字符编码 $file = "test.txt"; $handle = fopen($file, 'a'); //以追加写入的模式打开文件 fwrite($handle, 'https://www.php.cn/'); //写入内容 fclose($handle);//关闭文件 readfile($file); //读取并输出文件全部内容 ?>
Output results:
fopen($filename, $mode)The function can open a file according to the specified file mode
$mode. When
$mode is
a or
a , set the file pointer to the end of the file when opening the file; in this way, when writing, the data will be appended to Behind the existing data.
fwrite($handle, 'https://www.php.cn/') statement The function is to write the string "
https://www.php.cn/" into the already opened "test.txt".
readfile($file) function to get it directly.
Summary:
There are two ways to append data at the end of the file: one is to usefopen($file, 'a') and fwrite() function; the other is to use file_put_contents() and set the value of the third parameter of the function to "
FILE_APPEND".
《PHP interview questions summary (collection)》《php video tutorial》
The above is the detailed content of How to add data at the end of the file in php file operation. For more information, please follow other related articles on the PHP Chinese website!