用户下载的CSV文件,但文件大小约为500 KB

UPDATE: Look like it's my misunderstanding. The cause is on the library file that have problem with memory leak issue with PHP 5. So every time with heavy load like these is pass to the function, their document said **I must clear the memory each time I created a new object.

Apologize to my bad code investigation.


  • Engine: PHP 5.6 without framework
  • Browser: Chrome 68.0.3440.106
  • Server: XAMPP 3.2.2 bundle

What do I do for the code below is collect the data as assoc array, then sent to this function, and function will manage to write the file over network.

This function I find solution from stackoverflow and it worked for a small size of data.

Problem has occur with the data with very large size, I don't know how much of it. But it contains with over 50 rows and over 300 columns. Each cell contain with blank string or numeric, or text of Japanese words.

Code is work fine until the download process, I monitor with Chrome and when view with all download page (Ctrl+J), it always stuck at 492 KB and infinite loop of loading progress bar, until it reach the max_execution_time that I set to 30 minutes.

I have download part written like this:

function downloadArrayAsCsv($rows, $fileName) {

    // BOM (Byte Order Mark)!!!
    echo "\xEF\xBB\xBF";

    header_remove();
    header('Content-Type: text/csv; charset=Shift-JIS');
    header('Content-Disposition: attachment; filename="' . $fileName . '"');

    $fp = fopen('php://output', 'w');

    $_row = '';
    foreach ($rows as $row) {
        foreach($row as $k => $r) {

            if(is_string($r) && (intval($r)==0 || preg_match('/[A-Za-z\p{Hiragana}\p{Katakana}\p{Han}]+/', $r)) && !empty($r))
                $_row .= '"'.trim(preg_replace('/[\"]+/', '""', $r)).'"';
            else
                $_row .= $r;

            $_row .= ',';
        }
        $_row = substr($_row, 0, -1);
        $_row .= "
";

        fwrite($fp, $_row);
        $_row = '';
    }

    fclose($fp);
}

Try to edit your php.ini file:

memory_limit = 640M
max_input_time = 1000
post_max_size = 2000M
file_uploads = On
upload_max_filesize = 200M
max_file_uploads = 200
allow_url_fopen = On