How to read a large file line by line?

后端 未结 14 1008
[愿得一人]
[愿得一人] 2020-11-22 00:21

I want to read a file line by line, but without completely loading it in memory.

My file is too large to open in memory, and if try to do so I always get out of memo

相关标签:
14条回答
  • 2020-11-22 01:09

    Use buffering techniques to read the file.

    $filename = "test.txt";
    $source_file = fopen( $filename, "r" ) or die("Couldn't open $filename");
    while (!feof($source_file)) {
        $buffer = fread($source_file, 4096);  // use a buffer of 4KB
        $buffer = str_replace($old,$new,$buffer);
        ///
    }
    
    0 讨论(0)
  • 2020-11-22 01:11

    There is a file() function that returns an array of the lines contained in the file.

    foreach(file('myfile.txt') as $line) {
       echo $line. "\n";
    }
    
    0 讨论(0)
  • 2020-11-22 01:12
    <?php
    echo '<meta charset="utf-8">';
    
    $k= 1;
    $f= 1;
    $fp = fopen("texttranslate.txt", "r");
    while(!feof($fp)) {
        $contents = '';
        for($i=1;$i<=1500;$i++){
            echo $k.' -- '. fgets($fp) .'<br>';$k++;
            $contents .= fgets($fp);
        }
        echo '<hr>';
        file_put_contents('Split/new_file_'.$f.'.txt', $contents);$f++;
    }
    ?>
    
    0 讨论(0)
  • 2020-11-22 01:13
    if ($file = fopen("file.txt", "r")) {
        while(!feof($file)) {
            $line = fgets($file);
            # do same stuff with the $line
        }
        fclose($file);
    }
    
    0 讨论(0)
  • 2020-11-22 01:13

    You can use an object oriented interface class for a file - SplFileObject http://php.net/manual/en/splfileobject.fgets.php (PHP 5 >= 5.1.0)

    <?php
    
    $file = new SplFileObject("file.txt");
    
    // Loop until we reach the end of the file.
    while (!$file->eof()) {
        // Echo one line from the file.
        echo $file->fgets();
    }
    
    // Unset the file to call __destruct(), closing the file handle.
    $file = null;
    
    0 讨论(0)
  • 2020-11-22 01:13
    foreach (new SplFileObject(__FILE__) as $line) {
        echo $line;
    }
    
    0 讨论(0)
提交回复
热议问题