php Excel export large quantities of data solutions

1, the output stream derived by way PHP
php: // output is a write to the output stream, allows the program to operate like a file as write the output to the output stream, PHP will output content stream is sent to the web server and returned to the browser that initiated the request to save csv file
2, refresh the output buffer, to prevent problems caused by excessive data;
ob_flush (); flush (); with the use of
3, implementation code
/**
 * 导出CSV
 * @param        $rows
 * @param string $file_name
 */
function exportCsv($rows, $file_name = '数据')
{
    $filename =  $file_name. date('YmdHi') . '.csv'; //设置文件名
    header("Content-type:text/csv");
    header("Content-Disposition:attachment;filename=\"" . $filename . "\"");
    header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
    header('Expires:0');
    header ( 'Pragma: public' ); 

    $ FP     = the fopen ( 'PHP: // Output', 'A' );
     $ CNT    = 0; // counter 
    $ limit = 5000; // every $ limit line flush the Buffer 

    // add bomtou utf-8 normal display, but there will be problems after editing, to save as xls, xlsb, xlsx format 
    fwrite ( $ fp , "\ xEF \ xBB \ xBF" ); 

    foreach ( $ rows  aS  $ Row ) {
         $ cnt ++ ;
         IF ( $ limit == $ cnt ) { // flush the output buffer, to prevent problems caused by too much data 
            ob_flush ();
            flush();
            $cnt = 0;
        }
        fputcsv($fp, $row);
        unset($v);
        unset($row);
    }
}

 

Guess you like

Origin www.cnblogs.com/weedsyl/p/11646144.html