PHP获取文本文件的最后xx字节


PHP get the last xx bytes of a text file?

我有一些非常大的文本文件-每个100MB包含单行字符串(只有1行)。我想从每个字符中提取最后的xx字节/字符。我知道如何通过在字符串中读取它们,然后通过strpos()或substr()进行搜索来做到这一点,但这将需要一大块RAM,这对于这样一个小动作是不可取的。

有没有其他的方法,我可以只是提取,说,最后50个字节/字符的文本文件在PHP执行搜索之前?

谢谢!

可以使用fseek:

$fp = fopen('somefile.txt', 'r');
fseek($fp, -50, SEEK_END); // It needs to be negative
$data = fgets($fp, 50);

您可以通过使用第四个参数offset来实现file_get_contents

在PHP 7.1.0中,第四个参数offset可以为负。

// only negative seek if it "lands" inside the file or false will be returned
if (filesize($filename) > 50) {
    $data = file_get_contents($filename, false, null, -50);
}
else {
    $data = file_get_contents($filename);
}

Pre PHP 7.1.0:

$fsz = filesize($filename);
// only negative seek if it "lands" inside the file or false will be returned
if ($fsz > 50) {
    $data = file_get_contents($filename, false, null, $fsz - 50);
}
else {
    $data = file_get_contents($filename);
}