Home >Backend Development >PHP Tutorial >PHP reads and modifies a certain line of large files_PHP tutorial
I recently encountered an interesting problem, which is to modify a certain line of characters in a file. However, the file is too large and it is impossible to read it directly with file(). I use fgets to jump to the specified line, and use fwrite to modify a certain string:
In addition, today I also saw how to use SPL to operate:
$fp = new SplFileObject(d:/file.txt, r+);
//Go to the second line. The seek method parameters start counting from 0. I tested that the pointer points to the end of the line, so the third line is modified
$fp->seek(1);
//Get the current line content (second line)
$line = $fp->current();
//The following is the operation on the third line
$fp->fseek(2, SEEK_CUR);
$fp->fwrite(#);
The methods provided by SplFileObject are richer than basic file operation functions, including using key/value methods to traverse file lines, etc. SPL should be added to PHP5, and there are many other useful objects. Including arrays, file directory operations, exception handling, some basic type operations, etc. These functions are still being added. These methods can be extended by inheriting SPL to make it more convenient for us to handle the underlying operations.