PHP读取大文件的最后几行数据


/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/19
 * Time: 10:39
 */
function tail($filename, $num)
{
    if (!$fp = fopen($filename, 'r')) {
        echo "open file fail";
        return false;
    }
    $pos = -2;
    $eof = "";
    $str = "";
    while ($num > 0) {
        while ($eof != "\n") {//这里控制从文件的最后一行开始读
            if (!fseek($fp, $pos, SEEK_END)) {
                $eof = fgetc($fp);
                $pos--;
            } else {
                break;
            }
        }
        $str .= fgets($fp);//读取一行数据
        $eof = "";
        $num--;
    }
    return $str;
}

$filename = dirname(__FILE__) . "\\files\\laravel-2018-04-09.log";
echo nl2br(tail($filename, 4));



 

你可能感兴趣的:(php)