string replace in a large file with php

后端 未结 6 1896
借酒劲吻你
借酒劲吻你 2020-12-09 12:41

I am trying to do a string replace for entire file in PHP. My file is over 100MB so I have to go line by line and can not use file_get_contents(). Is there a

6条回答
  •  借酒劲吻你
    2020-12-09 13:17

    Get it a few lines at a time, dump the variable, get the next few lines.

    $fh = fopen("bigfile.txt", "flags");
    $num = 0;
    $length = 300;
    $filesize = filesize("bigfile.txt");
    
    while($num < $filesize)
    {
         $contents = fread($fh, $length);
         // .. do stuff ...
         $num = $num+$length;
         fseek($fh, $num);
    }
    
    fclose($fh);
    

    You are going to want to make sure that is correct (haven't tested). See the library on PHP Documentation.

    The tricky part is going to be writing back to the file. The first idea that pops into my mind is do the string replace, write the new content to another file, and then at the end, delete the old file and replace it with the new one.

提交回复
热议问题