Home > Article > Backend Development > PHP file writing, reading and replacing content_PHP tutorial
Perfectly implement PHP writing, reading, and replacing file content. Let me explain first, mainly used:
//写入文件 $str="This is a test from www.bkjia.comn"; // w表示以写入的方式打开文件,如果文件不存在,系统会自动建立 $file_pointer = fopen("aa.txt","a+"); fwrite($file_pointer,$str); fclose($file_pointer); //读取文件 $file_name="aa.txt"; $fp=fopen($file_name,'r'); while(!feof($fp)) { $buffer=fgets($fp,4096); //替换文件 $buffer = str_replace("bkjia","现代魔法",$buffer); $buffer = str_replace("This is a test","这是一个实例",$buffer); echo $buffer."<br />"; } fclose($fp);
fopen() function is used to open files in PHP. The first parameter of this function contains the name of the file to be opened, and the second parameter specifies which mode to use to open the file.
Mode Description
Note: If fopen() cannot open the specified file, it returns 0 (false).
Detect End-of-file
The feof() function detects whether the end of file (EOF) has been reached. The feof() function is useful when looping through data of unknown length. Note: In w, a and x modes, you cannot read open files!
if (feof($file)) echo "End of file";
fgets() function is used to read a file line by line from a file. After calling this function, the file pointer moves to the next line.