PHP fwrite() for writing a large string to file

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);

Alternative way of @Ayman Alkom solution.

function fwrite_stream($fp, $string) {
    for ($written = 0; $written < strlen($string); $written += $fwrite) {
        $fwrite = fwrite($fp, substr($string, $written));
        if ($fwrite === false) {
            return $written;
        }
    }
    return $written;
}

This should make a bit better performance.

But if you use this code for copy a big file,

Linux Command

"cat file1.txt file2.txt > file.txt" 

Window Command

"copy file1.txt+file1.txt file.txt"

Is the sollution.