我已经搜索了很长一段时间,但没有找到正确的解决方法。
我有一个日志文件,大小为100MB左右,大约140,000行文本。使用PHP,我想获取文件中的最后500行。
如何获取这500行呢?大多数函数都将文件读入内存,对于这种情况来说并不可行。最好避免执行系统命令。
我有一个日志文件,大小为100MB左右,大约140,000行文本。使用PHP,我想获取文件中的最后500行。
如何获取这500行呢?大多数函数都将文件读入内存,对于这种情况来说并不可行。最好避免执行系统命令。
$lastLines = `tail -n 500`;
请注意引号的使用,它会在BASH或类似环境中执行字符串并返回结果。
proc_open()
,只需监听tail -f
的输出。(或者也许没有必要使用PHP来执行你正在做的任何操作。) - Matthew$stream = popen("tail -n 500 -f $filename", "r");
您可以安全使用 fgets()
而无需担心它会占用 CPU。 - Matthewreturn
语句更改为return implode('', array_reverse($lines));
:function file_get_tail($filename, $num_lines = 10){
$file = fopen($filename, "r");
fseek($file, -1, SEEK_END);
for ($line = 0, $lines = array(); $line < $num_lines && false !== ($char = fgetc($file));) {
if($char === "\n"){
if(isset($lines[$line])){
$lines[$line][] = $char;
$lines[$line] = implode('', array_reverse($lines[$line]));
$line++;
}
}else
$lines[$line][] = $char;
fseek($file, -2, SEEK_CUR);
}
fclose($file);
if($line < $num_lines)
$lines[$line] = implode('', array_reverse($lines[$line]));
return array_reverse($lines);
}
例子:
file_get_tail('filename.txt', 500);
<?php
/**
Read last N lines from file.
@param $filename string path to file. must support seeking
@param $n int number of lines to get.
@return array up to $n lines of text
*/
function tail($filename, $n)
{
$buffer_size = 1024;
$fp = fopen($filename, 'r');
if (!$fp) return array();
fseek($fp, 0, SEEK_END);
$pos = ftell($fp);
$input = '';
$line_count = 0;
while ($line_count < $n + 1)
{
// read the previous block of input
$read_size = $pos >= $buffer_size ? $buffer_size : $pos;
fseek($fp, $pos - $read_size, SEEK_SET);
// prepend the current block, and count the new lines
$input = fread($fp, $read_size).$input;
$line_count = substr_count(ltrim($input), "\n");
// if $pos is == 0 we are at start of file
$pos -= $read_size;
if (!$pos) break;
}
fclose($fp);
// return the last 50 lines found
return array_slice(explode("\n", rtrim($input)), -$n);
}
var_dump(tail('/var/log/syslog', 50));
substr_count()
来查找新行。