How can I output a UTF-8 CSV in PHP that Excel will read properly?

后端 未结 30 2487
半阙折子戏
半阙折子戏 2020-11-22 06:08

I\'ve got this very simple thing that just outputs some stuff in CSV format, but it\'s got to be UTF-8. I open this file in TextEdit or TextMate or Dreamweaver and it displa

30条回答
  •  [愿得一人]
    2020-11-22 06:31

    **This is 100% works fine in excel for both Windows7,8,10 and also All Mac OS.**
    //Fix issues in excel that are not displaying characters containing diacritics, cyrillic letters, Greek letter and currency symbols.
    
    function generateCSVFile($filename, $headings, $data) {
    
        //Use tab as field separator
        $newTab  = "\t";
        $newLine  = "\n";
    
        $fputcsv  =  count($headings) ? '"'. implode('"'.$newTab.'"', $headings).'"'.$newLine : '';
    
        // Loop over the * to export
        if (! empty($data)) {
          foreach($data as $item) {
            $fputcsv .= '"'. implode('"'.$newTab.'"', $item).'"'.$newLine;
          }
        }
    
        //Convert CSV to UTF-16
        $encoded_csv = mb_convert_encoding($fputcsv, 'UTF-16LE', 'UTF-8');
    
        // Output CSV-specific headers
        header('Set-Cookie: fileDownload=true; path=/'); //This cookie is needed in order to trigger the success window.
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private",false);
        header("Content-Type: application/octet-stream");
        header("Content-Disposition: attachment; filename=\"$filename.csv\";" );
        header("Content-Transfer-Encoding: binary");
        header('Content-Length: '. strlen($encoded_csv));
        echo chr(255) . chr(254) . $encoded_csv; //php array convert to csv/excel
        exit;
    }
    

提交回复
热议问题