gpt4 book ai didi

php - 如何在 PHP 中只读取文本文件的最后 5 行?

转载 作者:IT王子 更新时间:2023-10-29 01:12:41 26 4
gpt4 key购买 nike

我有一个名为 file.txt 的文件,它通过添加行来更新。

我正在通过这段代码阅读它:

$fp = fopen("file.txt", "r");
$data = "";
while(!feof($fp))
{
$data .= fgets($fp, 4096);
}
echo $data;

然后出现大量行。我只想回显文件的最后 5 行

我该怎么做?


file.txt是这样的:

11111111111111
22222222222

33333333333333
44444444444

55555555555555
66666666666

最佳答案

对于一个大文件,使用 file() 将所有行读入一个数组有点浪费。以下是读取文件并维护最后 5 行缓冲区的方法:

$lines=array();
$fp = fopen("file.txt", "r");
while(!feof($fp))
{
$line = fgets($fp, 4096);
array_push($lines, $line);
if (count($lines)>5)
array_shift($lines);
}
fclose($fp);

您可以通过一些关于可能行长度的启发式方法来进一步优化这一点,方法是寻找一个位置,例如,距离末端大约 10 行,如果这不会产生 5 行,则再往前走。这是一个简单的实现,它证明了这一点:

//how many lines?
$linecount=5;

//what's a typical line length?
$length=40;

//which file?
$file="test.txt";

//we double the offset factor on each iteration
//if our first guess at the file offset doesn't
//yield $linecount lines
$offset_factor=1;


$bytes=filesize($file);

$fp = fopen($file, "r") or die("Can't open $file");


$complete=false;
while (!$complete)
{
//seek to a position close to end of file
$offset = $linecount * $length * $offset_factor;
fseek($fp, -$offset, SEEK_END);


//we might seek mid-line, so read partial line
//if our offset means we're reading the whole file,
//we don't skip...
if ($offset<$bytes)
fgets($fp);

//read all following lines, store last x
$lines=array();
while(!feof($fp))
{
$line = fgets($fp);
array_push($lines, $line);
if (count($lines)>$linecount)
{
array_shift($lines);
$complete=true;
}
}

//if we read the whole file, we're done, even if we
//don't have enough lines
if ($offset>=$bytes)
$complete=true;
else
$offset_factor*=2; //otherwise let's seek even further back

}
fclose($fp);

var_dump($lines);

关于php - 如何在 PHP 中只读取文本文件的最后 5 行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2961618/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com