Home > Article > Backend Development > PHP file reading and writing tutorial: Detailed introduction to the basic methods and processes of reading and writing
PHP file reading and writing tutorial: Detailed introduction to the basic methods and processes of reading and writing
Introduction:
When developing Web applications, the file Read and write operations are very basic and common operations. PHP provides a series of methods and functions to implement file reading and writing operations, and is very simple and easy to use. This tutorial will introduce in detail the basic methods and processes of reading and writing files in PHP, and give code examples.
1. Reading files
$file = fopen("test.txt", "r");
In the above example, we opened the file named test.txt and used the "r" mode, which means opening the file in read-only mode.
while (!feof($file)) { $line = fgets($file); echo $line . "<br>"; }
$content = fread($file, filesize("test.txt")); echo $content;
fclose($file);
2. Writing files
$file = fopen("test.txt", "w");
In the above example, we opened the file named test.txt and used the "w" mode, which means opening the file for writing. If the file does not exist, a new file is created. If the file already exists, the file contents will be cleared.
fputs($file, "Hello, World!");
fwrite($file, "Hello, World!");
fclose($file);
3. Complete example
The following is a complete example that demonstrates how to read the contents of a file and write the contents to another file.
// 打开待读取的文件 $readFile = fopen("source.txt", "r"); // 打开待写入的文件 $writeFile = fopen("target.txt", "w"); // 逐行读取文件内容并写入到目标文件 while (!feof($readFile)) { $line = fgets($readFile); fputs($writeFile, $line); } // 关闭文件 fclose($readFile); fclose($writeFile);
Summary:
This tutorial introduces in detail the basic methods and processes of reading and writing PHP files. When reading a file, you need to open the file first, and then choose an appropriate method to read the file content. When writing a file, you also need to open the file first, and then choose an appropriate method to write the file content. Finally, the file should be closed promptly to release system resources. I hope this tutorial is helpful to you and can be applied flexibly in actual development.
The above is the detailed content of PHP file reading and writing tutorial: Detailed introduction to the basic methods and processes of reading and writing. For more information, please follow other related articles on the PHP Chinese website!