php逐行读取文件内容

        $file = './runtime/logs/debug-2021-06-23.log';
        $line = 4;

        $length = 1024 * 1024;
        $returnTxt = null; // 初始化返回
        $i = 1; // 行数

        $handle = @fopen($file, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, $length);
                if($line > $i) $returnTxt .= $buffer . PHP_EOL. PHP_EOL;
                $i++;
            }
            fclose($handle);
        }

        // $content = file_get_contents($path);
        var_export($returnTxt);

在读取文本时,我们要注意一个事情,那就是换行符,应为我们在写文档时会手动换行,这个换行符需不需要保存就要看自己的需求了。

这里封装了两个方法,一个保留换行,一个不保留。$path为文件路径+文件名

1.不保留换行读取文件

 1 function read($path){
 2     $file = fopen($path, "r");
 3     $user=array();
 4     $i=0;
 5 //输出文本中所有的行,直到文件结束为止。
 6     while(! feof($file))
 7     {
 8         $user[$i]= trim(fgets($file));//fgets()函数从文件指针中读取一行
 9         $i++;
10     }
11     fclose($file);
12     $user=array_filter($user);
13     return $user;
14 }

2.保留换行

1 function read($path){
 2     $file = fopen($path, "r");
 3     $user=array();
 4     $i=0;
 5 //输出文本中所有的行,直到文件结束为止。
 6     while(! feof($file))
 7     {
 8         $user[$i]= fgets($file);//fgets()函数从文件指针中读取一行
 9         $i++;
10     }
11     fclose($file);
12     $user=array_filter($user);
13     return $user;
14 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值