35

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
4

19 に答える 19

51

大きなファイルの場合、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);
于 2010-06-02T21:21:17.473 に答える
22

テストされていないコードですが、動作するはずです:

$file = file("filename.txt");
for ($i = max(0, count($file)-6); $i < count($file); $i++) {
  echo $file[$i] . "\n";
}

を呼び出すmaxと、6 行未満のファイルが処理されます。

于 2010-06-02T21:16:10.980 に答える
17

Linux システムを使用している場合は、次のようにできます。

$lines = `tail -5 /path/to/file.txt`;

それ以外の場合は、次のように行を数えて最後の 5 つを取得する必要があります。

$all_lines = file('file.txt');
$last_5 = array_slice($all_lines , -5);
于 2010-06-02T21:27:33.153 に答える
14

で大きなファイルを開くとfile()、大きな配列が生成され、かなりの量のメモリが予約されます。

SplFileObject各行を反復処理するため、メモリ コストを削減できます。

seekメソッド (of ) を使用してseekableiterator、最後の行を取得します。次に、現在のキー値を 5 減算する必要があります。

最後の行を取得するには、 を使用しますPHP_INT_MAX。(はい、これは回避策です。)

$file = new SplFileObject('large_file.txt', 'r');

$file->seek(PHP_INT_MAX);

$last_line = $file->key();

$lines = new LimitIterator($file, $last_line - 5, $last_line);

print_r(iterator_to_array($lines));
于 2016-01-24T20:58:33.123 に答える
14
function ReadFromEndByLine($filename,$lines)
{

        /* freely customisable number of lines read per time*/
        $bufferlength = 5000;

        $handle = @fopen($filename, "r");
        if (!$handle) {
                echo "Error: can't find or open $filename<br/>\n";
                return -1;
        }

        /*get the file size with a trick*/
        fseek($handle, 0, SEEK_END);
        $filesize = ftell($handle);

        /*don't want to get past the start-of-file*/
        $position= - min($bufferlength,$filesize);

        while ($lines > 0) {

                if ($err=fseek($handle,$position,SEEK_END)) {  /* should not happen but it's better if we check it*/
                        echo "Error $err: something went wrong<br/>\n";
                        fclose($handle);
                        return $lines;
                }

                /* big read*/
                $buffer = fread($handle,$bufferlength);

                /* small split*/
                $tmp = explode("\n",$buffer);

                /*previous read could have stored a partial line in $aliq*/
                if ($aliq != "") {

                                /*concatenate current last line with the piece left from the previous read*/
                                $tmp[count($tmp)-1].=$aliq;
                }

                /*drop first line because it may not be complete*/
                $aliq = array_shift($tmp);

                $read = count($tmp);
                if ( $read >= $lines ) {   /*have read too much!*/

                        $tmp2 = array_slice($tmp,$read-$n);
                        /* merge it with the array which will be returned by the function*/
                        $lines = array_merge($tmp2,$lines);

                        /* break the cycle*/
                        $lines = 0;
                } elseif (-$position >= $filesize) {  /* haven't read enough but arrived at the start of file*/

                        //get back $aliq which contains the very first line of the file
                        $lines = array_merge($aliq,$tmp,$lines);

                        //force it to stop reading
                        $lines = 0;

                } else {              /*continue reading...*/

                        //add the freshly grabbed lines on top of the others
                        $lines = array_merge($tmp,$lines);

                        $lines -= $read;

                        //next time we want to read another block
                        $position -= $bufferlength;

                        //don't want to get past the start of file
                        $position = max($position, -$filesize);
                }
        }
        fclose($handle);

        return $lines;
}

これは大きなファイルの場合は高速ですが、単純なタスクの場合は大量のコードになります。大きなファイルがある場合は、これを使用してください

ReadFromEndByLine('myFile.txt',6);

于 2010-06-02T21:19:29.787 に答える
12

これはよくある面接の質問です。昨年、この質問を受けたときに私が書いたものは次のとおりです。Stack Overflow で入手したコードは、Creative Commons Share-Alikeでライセンスが付与されており、帰属が必要であることに注意してください。

<?php

/**
 * Demonstrate an efficient way to search the last 100 lines of a file
 * containing roughly ten million lines for a sample string. This should
 * function without having to process each line of the file (and without making
 * use of the “tail” command or any external system commands). 
 * Attribution: https://stackoverflow.com/a/2961731/3389585
 */

$filename = '/opt/local/apache2/logs/karwin-access_log';
$searchString = 'index.php';
$numLines = 100;
$maxLineLength = 200;

$fp = fopen($filename, 'r');

$data = fseek($fp, -($numLines * $maxLineLength), SEEK_END);

$lines = array();
while (!feof($fp)) {
  $lines[] = fgets($fp);
}

$c = count($lines);
$i = $c >= $numLines? $c-$numLines: 0;
for (; $i<$c; ++$i) {
  if ($pos = strpos($lines[$i], $searchString)) {
    echo $lines[$i];
  }
}

このソリューションでは、行の最大長を想定しています。インタビュアーは、私がその仮定を立てることができず、私が選択した最大長よりも潜在的に長い行に対応しなければならなかった場合、どのように問題を解決するかを尋ねました.

私は彼に、どんなソフトウェアプロジェクトでも特定の仮定をしなければなら$cないが、必要な行数よりも少ないかどうかをテストし、そうでない場合は、fseek()十分な行数が得られるまでさらに段階的に (毎回 2 倍に) 戻すことができると言いました。

于 2010-06-02T21:27:44.293 に答える
6

これは使用しないfile()ため、巨大なファイルの場合により効率的です。

<?php
function read_backward_line($filename, $lines, $revers = false)
{
    $offset = -1;
    $c = '';
    $read = '';
    $i = 0;
    $fp = @fopen($filename, "r");
    while( $lines && fseek($fp, $offset, SEEK_END) >= 0 ) {
        $c = fgetc($fp);
        if($c == "\n" || $c == "\r"){
            $lines--;
            if( $revers ){
                $read[$i] = strrev($read[$i]);
                $i++;
            }
        }
        if( $revers ) $read[$i] .= $c;
        else $read .= $c;
        $offset--;
    }
    fclose ($fp);
    if( $revers ){
        if($read[$i] == "\n" || $read[$i] == "\r")
            array_pop($read);
        else $read[$i] = strrev($read[$i]);
        return implode('',$read);
    }
    return strrev(rtrim($read,"\n\r"));
}
//if $revers=false function return->
//line 1000: i am line of 1000
//line 1001: and i am line of 1001
//line 1002: and i am last line
//but if $revers=true function return->
//line 1002: and i am last line
//line 1001: and i am line of 1001
//line 1000: i am line of 1000
?>
于 2012-05-23T00:38:03.617 に答える
3

この関数は、4GB 未満の非常に大きなファイルに対して機能します。速度は、一度に 1 バイトずつ読み取るのではなく、大量のデータを読み取って行を数えることから得られます。

// Will seek backwards $n lines from the current position
function seekLineBackFast($fh, $n = 1){
    $pos = ftell($fh);
    if ($pos == 0)
        return false;

    $posAtStart = $pos;

    $readSize = 2048*2;
    $pos = ftell($fh);
    if(!$pos){
            fseek($fh, 0, SEEK_SET);
            return false;
    }

    // we want to seek 1 line before the line we want.
    // so that we can start at the very beginning of the line
    while ($n >= 0) {
        if($pos == 0)
                    break;
            $pos -= $readSize;
            if($pos <= 0){
                    $pos = 0;
            }

            // fseek returns 0 on success and -1 on error
            if(fseek($fh, $pos, SEEK_SET)==-1){
                    fseek($fh, 0, SEEK_SET);
                    break;
            }
            $data = fread($fh, $readSize);
            $count = substr_count($data, "\n");
            $n -= $count;

            if($n < 0)
                    break;
    }
    fseek($fh, $pos, SEEK_SET);
    // we may have seeked too far back
    // so we read one line at a time forward
    while($n < 0){
            fgets($fh);
            $n++;
    }
    // just in case?
    $pos = ftell($fh);
    if(!$pos)
        fseek($fh, 0, SEEK_SET);

    // check that we have indeed gone back
    if ($pos >= $posAtStart)
        return false;

    return $pos;
}

上記の関数を実行した後、ループ内で fgets() を実行して、$fh から一度に各行を読み取ることができます。

于 2012-12-18T16:08:04.373 に答える
3

PHP のfile()関数は、ファイル全体を配列に読み込みます。このソリューションでは、最小限の入力が必要です。

$data = array_slice(file('file.txt'), -5);

foreach ($data as $line) {
    echo $line;
}
于 2010-06-02T21:21:52.977 に答える
1

You can use my small helper library (2 functions)

https://github.com/jasir/file-helpers

次に、次を使用します。

//read last 5 lines
$lines = \jasir\FileHelpers\FileHelpers::readLastLines($pathToFile, 5);
于 2013-01-20T01:11:31.770 に答える
0

私はこれをテストしました。わたしにはできる。

function getlast($filename,$linenum_to_read,$linelength){

   // this function takes 3 arguments;


   if (!$linelength){ $linelength = 600;}
$f = fopen($filename, 'r');
$linenum = filesize($filename)/$linelength;

    for ($i=1; $i<=($linenum-$linenum_to_read);$i++) {
    $data = fread($f,$linelength);
    }
echo "<pre>";       
    for ($j=1; $j<=$linenum_to_read+1;$j++) {
    echo fread($f,$linelength);
    }

echo "</pre><hr />The filesize is:".filesize("$filename");
}

getlast("file.txt",6,230);


?>
于 2010-11-29T05:00:43.863 に答える
0

これが私の解決策です:

/**
 *
 * Reads N lines from a file
 *
 * @param type $file       path
 * @param type $maxLines   Count of lines to read
 * @param type $reverse    set to true if result should be reversed.
 * @return string
 */
public function readLinesFromFile($file, $maxLines, $reverse=false)
{
    $lines = file($file);

    if ($reverse) {
        $lines = array_reverse($lines);
    }

    $tmpArr = array();

    if ($maxLines > count($lines))
        exit("\$maxLines ist größer als die Anzahl der Zeilen in der Datei.");

    for ($i=0; $i < $maxLines; $i++) {
        array_push($tmpArr, $lines[$i]);
    }

    if ($reverse) {
        $tmpArr = array_reverse($tmpArr);
    }

    $out = "";
    for ($i=0; $i < $maxLines; $i++) {
        $out .= $tmpArr[$i] . "</br>";
    }

    return $out;
}
于 2018-07-18T12:20:08.857 に答える
-2

行が CR または LF で区切られている場合は、$data 変数を分解してみてください

$lines = explode("\n", $data);

$lines は最終的に配列になるはずであり、 sizeof() を使用してレコード数を計算し、最後の 5 つを取得できます。

于 2010-06-02T21:12:36.913 に答える