使用PHP读取日志文件,当文件比较大的时候,会报内存不足,因此应该部分读取,读取指定的行数的数据,以下是读取函数
private function read_log($file, $num=20){ $handle = fopen($file, "r"); $pos = -2; $eof = ""; $beginning = false; //当总行数小于Num时,判断是否到第一行了 $lines = array(); while($num > 0){ while($eof != "\n"){ if(fseek($handle, $pos, SEEK_END) == -1) { //fseek成功返回0,失败返回-1 $beginning = true; //到达文件头部,开关打开 break; } $eof = fgetc($handle); $pos --; } array_unshift($lines,fgets($handle)); if($beginning){ break; } //这一句,只能放上一句后,因为到文件头后,把第一行读取出来再跳出整个循环 $eof = ""; $num--; } fclose($handle); return array_reverse($lines); }
引用并显示到页面 public function show_log($line = 50) { $line = intval($line); $line = $line <= 0 ? 50 : $line; //文件路径 $file = 'test.txt'; if(!file_exists($file)) exit('找不到日志文件'); $result = $this->read_log($file, $line); $html=""; foreach($result as $line){ if(strpos($line,"error")){ $line="<font color='red'>".$line."</font>"; } $html.="<div class='line'>".$line."<div>"; } echo $html; }
