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.
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
<?php header("Content-Type: text/html;charset=utf-8"); //设置字符编码 $file = "test.txt"; $handle = fopen($file, 'w'); //打开文件 fwrite($handle, 'HELLO PHP!'); //写入内容 fclose($handle);//关闭文件 readfile($file); //读取并输出文件全部内容 ?>
Example 2: Add data at the end of the file
<?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); //读取并输出文件全部内容 ?>
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:
<?php header("Content-Type: text/html;charset=utf-8"); //设置字符编码 $file = "test.txt"; file_put_contents($file, '欢迎来到PHP中文网!'); //写入内容 readfile($file); //读取并输出文件全部内容 ?>
<?php header("Content-Type: text/html;charset=utf-8"); //设置字符编码 $file = "test.txt"; file_put_contents($file, '欢迎来到PHP中文网!',FILE_APPEND); //在文件结尾写入内容 readfile($file); //读取并输出文件全部内容 ?>
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!