我應該用什麼php函數來計算大文件的第5行,因爲第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"
我應該用什麼php函數來計算大文件的第5行,因爲第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"
打開文件到一個手柄:
$handle = fopen("someFilePath", "r");
然後讀取所述第一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
注這是流式傳輸,因此它不會加載整個文件。
如果你想讀每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();
}
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;
}
請在將來包含更多細節。僅包含鏈接的答案往往不太有用,因爲網站移動或內容更改。 – jwiscarson
您可以發佈什麼樣的文件看起來像一個例子,你想,你得到的結果做什麼?您是否正在嘗試讀取文本文件第五行的整數,或者通過電線傳輸該行上的任何文本所需的帶寬? –
你想閱讀文件中的第5行,或者*每行* 5行嗎?給出一個(簡短的)文件例子和你想要讀的內容。 – salathe
我想統計大文件中每5行的帶寬 - 數據示例:103.239.234.105 - [2007-04-01 00:42:21]「GET articles/learn_PHP_basics HTTP/1.0」200 12729 「Mozilla/4.0」 – Sky12