php gets the last N lines of data from the file

不言
Release: 2023-03-23 07:54:02
Original
1830 people have browsed it

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();
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!