我应该用什么函数来读取大文件的第5行?

时间:2011-11-09 20:43:11

标签: php file-io

我应该使用什么PHP函数来计算大文件的第5行,因为第5行是带宽?

数据示例:

103.239.234.105 -- [2007-04-01 00:42:21] "GET articles/learn_PHP_basics HTTP/1.0" 200 12729 "Mozilla/4.0"

3 个答案:

答案 0 :(得分:1)

如果您想阅读每5行,您可以使用SplFileObject让生活变得更轻松(比fopen/fgets/fclose系列功能)。

$f = new SplFileObject('myreallybigfile.txt');

// Read ahead so that if the last line in the file is a 5th line, we echo it.
$f->setFlags(SplFileObject::READ_AHEAD);

// Loop over every 5th line starting at line 5 (offset 4).
for ($f->rewind(), $f->seek(4); $f->valid(); $f->seek($f->key()+5)) {
    echo $f->current();
}

答案 1 :(得分:0)

将文件打开到句柄中:

$handle = fopen("someFilePath", "r");

然后读取前5行,只保存第5行:

$i = 0;
$fifthLine = null;
while (($buffer = fgets($handle, 4096)) !== false) {
    if $i++ >= 5) {
        $fifthLine = $buffer;
        break;
    }
}
fclose($handle);
if ($i < 5); // uh oh, there weren't 5 lines in the file!
//$fifthLine should contain the 5th line in the file

请注意,这是流式传输,因此不会加载整个文件。

答案 2 :(得分:0)

http://tekkie.flashbit.net/php/tail-functionality-in-php

<?php

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