$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 }