php获取文件的最后N行数据

不言
不言 原创
2023-03-23 07:54:02 1401浏览

本篇文章介绍的内容是php获取文件的最后N行数据,现在分享给大家,也可以给有需要的朋友一个参考

GitHub源码
代码是基于以下问题,给出的解决方案:
用php写一个函数,获取一个文本文件最后$n行内容,要求尽可能效率更高,并可以跨平台使用

我理解的可以跨平台使用,是说的文件在windows平台和linux平台的行结束符不一致问题,在代码中我们没有体现这种不同。全部是在linux系统下的代码。跨平台问题还需要理解?

<?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();

相关推荐:

PHP获取数组中指定一列的方法

PHP获取用户IP地址的方法

以上就是php获取文件的最后N行数据的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。