How to add data at the end of the file in php file operation

青灯夜游
Release: 2023-03-11 22:12:02
Original
5636 people have browsed it

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:

How to add data at the end of the file in php file operation

We want to add the following piece of data at the end of the file:

https://www.php.cn/
Copy after login

Let’s take a look at the implementation code:

<?php
header("Content-Type: text/html;charset=utf-8");    //设置字符编码
$file = "test.txt";
$handle = fopen($file, &#39;a&#39;);                 //以追加写入的模式打开文件
fwrite($handle, &#39;https://www.php.cn/&#39;);    //写入内容
fclose($handle);//关闭文件
readfile($file);   //读取并输出文件全部内容
?>
Copy after login

Output results:

How to add data at the end of the file in php file operation

##Key code analysis:

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.

The fwrite() function can write a string to an open file, so the

fwrite($handle, 'https://www.php.cn/') statement The function is to write the string "https://www.php.cn/" into the already opened "test.txt".

After writing is completed, use the fclose() function to close the file. If you want to get the new content in the "test.txt" file, use the

readfile($file) function to get it directly.

Summary:

There are two ways to append data at the end of the file: one is to use

fopen($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".

Okay, that’s all. If you want to know anything else, you can click this. → →

Basic operation of PHP files

## Recommended:

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template