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

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

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

<?php
header("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();
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值