【问题标题】:PHP get the last xx bytes of a text file?PHP获取文本文件的最后xx字节?
【发布时间】:2013-04-14 08:12:33
【问题描述】:

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

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

谢谢!

【问题讨论】:

标签: php file search


【解决方案1】:

你可以使用fseek:

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

【讨论】:

【解决方案2】:

您可以通过使用第四个参数offset 来使用file_get_contents 来做到这一点。

PHP 7.1.0 及以上版本:

在 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);
}

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);
}

【讨论】:

    猜你喜欢
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多