php export big data with csv

header ( "Content-type:application/vnd.ms-excel" );  
header ( "Content-Disposition:filename=" . iconv ( "UTF-8", "GB2312//IGNORE", "查询用户列表" ) . ".csv" );     
$out = $column_name;  
echo iconv ( "UTF-8", "GB2312//IGNORE", $out );  
 
$pre_count = 20000;  
for ($i=0;$i<intval($total_export_count/$pre_count)+1;$i++){  
    $export_data = $db->getAll($sql." limit ".strval($i*$pre_count).",{$pre_count}");  
    foreach ( $export_data as $key => $item ) {  
        echo iconv ( "UTF-8", "GB2312//IGNORE", $item[0] ).',';

        echo iconv ( "UTF-8", "GB2312//IGNORE", csvHandlerStr($item[1]) ).",\n"; //If there is a design comma in the content, it needs to be converted
    }  
      
    // Will have been written to The data storage variable in csv is destroyed and the memory is released  
       unset($export_data);  
}  
 
exit (); 

 

 

function csvHandlerStr( $string ) {
    //If there are commas in the csv format, the whole is enclosed in double quotation marks; if there are double quotation marks in it, replace it with two double quotation marks, so that there will be no problem with the exported format.
    //If There are commas
    if ( strpos( $string, ',' ) ) {
        //If there are double quotes, escape the double quotes first to avoid escaping errors after adding double quotes on both sides
        if ( strpos( $string, '"' ) ) {
            $string = str_replace( '"', '""', $string );
        }
        // after escaping comma
        $string = '"' . $string . '"';
    }

    return $string;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325277743&siteId=291194637