Search code examples
phpfwritelarge-files

PHP fwrite() for writing a large string to file


I have to write a large string 10MB to file, and I am using this line to achieve that:

fwrite($file, $content);

the problem is: not the whole string is written to the file, and limited to a specific limit.

and fwrite always return 7933594.


Solution

  • Yes, fwrite function is limited to length, and for a large files you may split the file to a smaller pieces like the following:

        $file   = fopen("file.json", "w");
    
        $pieces = str_split($content, 1024 * 4);
        foreach ($pieces as $piece) {
            fwrite($file, $piece, strlen($piece));
        }
    
        fclose($file);