PHP file read and write operation examples and analysis
In web development, file operation is one of the very common tasks. As a popular server-side programming language, PHP provides a wealth of file read and write operation functions, which can easily read, write, and modify files. This article will introduce some commonly used PHP file read and write operation functions and give corresponding code examples to help readers better understand and apply these functions.
In PHP, the commonly used file reading functions are file_get_contents()
and fread()
. The file_get_contents()
function can read the entire file contents into a string, while the fread()
function needs to read the file contents step by step through a loop.
// 使用file_get_contents()读取文件 $file_content = file_get_contents('example.txt'); echo $file_content; // 使用fread()读取文件 $file_handle = fopen('example.txt', 'r'); while (!feof($file_handle)) { $file_content = fread($file_handle, 1024); echo $file_content; } fclose($file_handle);
For file writing operations, PHP provides file_put_contents()
and fwrite()
function. The file_put_contents()
function can directly write strings into a file, while the fwrite()
function needs to open the file first and then gradually write data.
// 使用file_put_contents()写入文件 $file_content = 'Hello, world!'; file_put_contents('example.txt', $file_content); // 使用fwrite()写入文件 $file_handle = fopen('example.txt', 'w'); $file_content = 'Hello, world!'; fwrite($file_handle, $file_content); fclose($file_handle);
If you need to append data to the end of an existing file, you can use file_put_contents()
## of the function #FILE_APPEND parameter, or use the
a mode of the
fopen() function.
// 使用file_put_contents()追加写入文件 $file_content = 'Hello, world!'; file_put_contents('example.txt', $file_content, FILE_APPEND); // 使用fopen()追加写入文件 $file_handle = fopen('example.txt', 'a'); $file_content = 'Hello, world!'; fwrite($file_handle, $file_content); fclose($file_handle);
// 修改文件内容 $file_handle = fopen('example.txt', 'r+'); $file_content = fread($file_handle, filesize('example.txt')); $file_content = str_replace('Hello', 'Hi', $file_content); rewind($file_handle); fwrite($file_handle, $file_content); fclose($file_handle);
The above is the detailed content of PHP file read and write operation examples and analysis. For more information, please follow other related articles on the PHP Chinese website!