PHP fwrite() for writing a large string to file

拟墨画扇 提交于 2019-12-01 04:13:10

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/33500998/php-fwrite-for-writing-a-large-string-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!