Perfect for PHP writing, reading, and replacing file content. First, I will explain it in the following ways:
- Fopen ("file name. Extension", "Operation Method ")
- Fwrite (Read File, "written file ");
- Fclose (Open object variable );
// Write the file $ str = "This is a test from www. bkjia. comn "; // w indicates opening the file as a write. If the file does not exist, the system automatically creates $ file_pointer = fopen (" aa.txt "," a + "); fwrite ($ file_pointer, $ str); fclose ($ file_pointer); // read the file $ file_name = "aa.txt"; $ fp = fopen ($ file_name, 'R '); while (! Feof ($ fp) {$ buffer = fgets ($ fp, 4096); // Replace the file $ buffer = str_replace ("bkjia", "modern magic", $ buffer ); $ buffer = str_replace ("This is a test", "This is an instance", $ buffer); echo $ buffer. "<br/>" ;}fclose ($ fp );
Fopen ()
The fopen () function is used to open a file in PHP. The first parameter of this function contains the name of the file to be opened, and the second parameter specifies the mode used to open the file.
Mode description
- R read-only. Start at the beginning of the file.
- R + read/write. Start at the beginning of the file.
- W write only. Open and clear the file content. If the file does not exist, create a new file.
- W + read/write. Open and clear the file content. If the file does not exist, create a new file.
- A append. Open and write to the end of the file. If the file does not exist, create a new file.
- A + Read/append. Write content to the end of the file to keep the file content.
- X write only. Create a new file. If the object already exists, FALSE is returned.
- X + read/write. Create a new file. If the file already exists, FALSE and an error are returned.
NOTE: If fopen () cannot open the specified file, 0 (false) is returned ).
Feof ()
Detect End-of-file
The feof () function checks whether the object has reached the end of the object (EOF). The feof () function is useful when traversing data with unknown lengths cyclically. Note: In w, a, and x modes, you cannot read open files!
if (feof($file)) echo "End of file";
Fgets ()
The fgets () function is used to read objects row by row from objects. After this function is called, the file pointer is moved to the next row.