Microsoft Excel mangles Diacritics in .csv files?

后端 未结 22 2020
粉色の甜心
粉色の甜心 2020-11-22 05:02

I am programmatically exporting data (using PHP 5.2) into a .csv test file.
Example data: Numéro 1 (note the accented e). The data is utf-8 (

22条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 05:17

    Below is the PHP code I use in my project when sending Microsoft Excel to user:

      /**
       * Export an array as downladable Excel CSV
       * @param array   $header
       * @param array   $data
       * @param string  $filename
       */
      function toCSV($header, $data, $filename) {
        $sep  = "\t";
        $eol  = "\n";
        $csv  =  count($header) ? '"'. implode('"'.$sep.'"', $header).'"'.$eol : '';
        foreach($data as $line) {
          $csv .= '"'. implode('"'.$sep.'"', $line).'"'.$eol;
        }
        $encoded_csv = mb_convert_encoding($csv, 'UTF-16LE', 'UTF-8');
        header('Content-Description: File Transfer');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="'.$filename.'.csv"');
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: '. strlen($encoded_csv));
        echo chr(255) . chr(254) . $encoded_csv;
        exit;
      }
    

    UPDATED: Filename improvement and BUG fix correct length calculation. Thanks to TRiG and @ivanhoe011

提交回复
热议问题