Mat*_*ley 42
最简单的天真解决方案很简单:
$file = "/path/to/file";
$data = file($file);
$line = $data[count($data)-1];
Run Code Online (Sandbox Code Playgroud)
但是,这会将整个文件加载到内存中.可能是一个问题(或不是).更好的解决方案是:
$file = escapeshellarg($file); // for the security concious (should be everyone!)
$line = `tail -n 1 $file`;
Run Code Online (Sandbox Code Playgroud)
Tom*_*lak 14
这看起来就像你在寻找:
它实现了一个函数,该函数使用带有负索引的fseek()从末尾汇总文件.您可以定义要返回的行数.
该代码也可作为GitHub上的Gist:
// full path to text file
define("TEXT_FILE", "/home/www/default-error.log");
// number of lines to read from the end of file
define("LINES_COUNT", 10);
function read_file($file, $lines) {
//global $fsize;
$handle = fopen($file, "r");
$linecounter = $lines;
$pos = -2;
$beginning = false;
$text = array();
while ($linecounter > 0) {
$t = " ";
while ($t != "\n") {
if(fseek($handle, $pos, SEEK_END) == -1) {
$beginning = true;
break;
}
$t = fgetc($handle);
$pos --;
}
$linecounter --;
if ($beginning) {
rewind($handle);
}
$text[$lines-$linecounter-1] = fgets($handle);
if ($beginning) break;
}
fclose ($handle);
return array_reverse($text);
}
$fsize = round(filesize(TEXT_FILE)/1024/1024,2);
echo "<strong>".TEXT_FILE."</strong>\n\n";
echo "File size is {$fsize} megabytes\n\n";
echo "Last ".LINES_COUNT." lines of the file:\n\n";
$lines = read_file(TEXT_FILE, LINES_COUNT);
foreach ($lines as $line) {
echo $line;
}
Run Code Online (Sandbox Code Playgroud)
小智 8
define('YOUR_EOL', "\n");
$fp = fopen('yourfile.txt', 'r');
$pos = -1; $line = ''; $c = '';
do {
$line = $c . $line;
fseek($fp, $pos--, SEEK_END);
$c = fgetc($fp);
} while ($c != YOUR_EOL);
echo $line;
fclose($fp);
Run Code Online (Sandbox Code Playgroud)
这样更好,因为它没有将完整的文件加载到内存中......
将YOUR_EOL设置为正确的行结尾,如果使用与脚本所在的OS的默认行结尾相同的行结尾,则可以使用常量PHP_EOL.
小智 5
function seekLastLine($f) {
$pos = -2;
do {
fseek($f, $pos--, SEEK_END);
$ch = fgetc($f);
} while ($ch != "\n");
}
Run Code Online (Sandbox Code Playgroud)
-2因为最后一个字符可以是\n