How to export data to CSV format?

Cyclic array data may be directly used  fwrite , or  fputs the good data assembled for each row written to the file.

A better way is to use  fputcsv the function, can be saved directly to a data array in a row separated by commas.

Direct look at the code:

function downloadAsCsvFile( array &$csvTitle, array &$csvData, $fileName='' ) {
    if(empty($fileName)){ //保存的文件名称
      $fileName = 'download_'.date('Ymd_His');
    }
    header('Content-type: application/csv');
    header('Content-Transfer-Encoding: binary; charset=utf-8');
    header('Content-Disposition: attachment; filename='.$fileName.'.csv');
    $fp The fopen = ( " PHP: // Output " , ' W ' );
     // generate BOM header 
    fputs (FP $, $ = BOM (CHR ( 0xEF .) CHR ( 0xBB .) CHR ( 0xBF )));
     // generated The title bar 
    fputcsv (FP $, $ csvTitle);
     the foreach ($ CSVData AS $ Row) { 
        fputcsv (FP $, $ Row); 
    } 
    Exit (); 
}

----------------
Disclaimer: This article is the original article CSDN bloggers "Wang123net", and follow CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement. .
Original link: https: //blog.csdn.net/cnwyt/article/details/84874471

Guess you like

Origin www.cnblogs.com/zhangzhijian/p/11977233.html