The content introduced in this article is the last N lines of data obtained from the file by php. Now I share it with everyone, and can also give a reference to friends in need
GitHub source code
The code is based on the following issues, Solution given:
Use PHP to write a function to get the last $n lines of a text file. It needs to be as efficient as possible and can be used across platforms.
What I understand is that it can be used across platforms. It means that the file can be used on the windows platform and There is an issue with inconsistent line terminators on the Linux platform. We did not reflect this difference in the code. All are codes under the linux system. Do you still need to understand cross-platform issues?
<?phpheader("content-type:text/html;charset=utf-8");class GetFileLastNumRow{ private $filePath; private $fileMode = 'r'; private $rowNum = 3; public function __construct(array $config) { foreach ($config as $key => $value) { $this->$key = $value; } } public function run() { try { $handle = fopen($this->filePath, $this->fileMode); fseek($handle, -1, SEEK_END); $contents = ""; $rowCount = 0; do { if (($str = fgetc($handle)) == "\n") { $rowCount++; } $contents = $str.$contents; fseek($handle, -2, SEEK_CUR); } while ($rowCount < $this->rowNum); var_export(trim($contents, "\n")); fclose($handle); } catch(\Exception $e) { var_export($e->getMessage()); } } }class Test{ public function run() { $filePath = './TestData/GetFileLastNumRow/test.data'; $getFileLastNumRow = new GetFileLastNumRow(compact('filePath')); $getFileLastNumRow->run(); } }$test = new Test();$test->run();
Related recommendations:
PHP method to get a specified column in an array
PHP to get the user IP Address method
The above is the detailed content of php gets the last N lines of data from the file. For more information, please follow other related articles on the PHP Chinese website!