Home >Backend Development >PHP Tutorial >php gets the last N lines of data from the file

php gets the last N lines of data from the file

不言
不言Original
2018-04-04 10:01:461862browse

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 = &#39;r&#39;;    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 = &#39;./TestData/GetFileLastNumRow/test.data&#39;;        $getFileLastNumRow = new GetFileLastNumRow(compact(&#39;filePath&#39;));        $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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn