PHP what is the best way to write data to middle of file without rewriting file

后端 未结 3 845
说谎
说谎 2020-11-29 10:31

I am working with large text files in php (1GB+), I am using

file_get_contents(\"file.txt\", NULL, NULL, 100000000,100); 

To get data from

3条回答
  •  天涯浪人
    2020-11-29 11:16

    A variant on Baba's answer, not sure if it would be more efficient when working with larger files:

    function injectData($file, $data, $position) {
        $fpFile = fopen($file, "rw+");
        $fpTemp = fopen('php://temp', "rw+");
        stream_copy_to_stream($fpFile, $fpTemp, $position);
        fwrite($fpTemp, $data);
        stream_copy_to_stream($fpFile, $fpTemp, -1, $position);
    
        rewind($fpFile);
        rewind($fpTemp);
        stream_copy_to_stream($fpTemp, $fpFile);
    
        fclose($fpFile);
        fclose($fpTemp);
    }
    
    injectData('testFile.txt', 'JKL', 3);
    

    Variant of my earlier method that eliminates one of the stream_copy_to_stream() calls, so should be a shade faster:

    function injectData3($file, $data, $position) {
        $fpFile = fopen($file, "rw+");
        $fpTemp = fopen('php://temp', "rw+");
        stream_copy_to_stream($fpFile, $fpTemp, -1, $position);
        fseek($fpFile, $position);
        fwrite($fpFile, $data);
        rewind($fpTemp);
        stream_copy_to_stream($fpTemp, $fpFile);
    
        fclose($fpFile);
        fclose($fpTemp);
    }
    

提交回复
热议问题