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

后端 未结 30 2476
半阙折子戏
半阙折子戏 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:12

    I just tried these headers and got Excel 2013 on a Windows 7 PC to import the CSV file with special characters correctly. The Byte Order Mark (BOM) was the final key that made it work.

    
        header('Content-Encoding: UTF-8');
        header('Content-type: text/csv; charset=UTF-8');
        header("Content-disposition: attachment; filename=filename.csv");
        header("Pragma: public");
        header("Expires: 0");
        echo "\xEF\xBB\xBF"; // UTF-8 BOM
    
    
    0 讨论(0)
  • 2020-11-22 06:14

    You have to use the encoding "Windows-1252".

    header('Content-Encoding: Windows-1252');
    header('Content-type: text/csv; charset=Windows-1252');
    header("Content-Disposition: attachment; filename={$filename}");
    

    Maybe you have to convert your strings:

    private function convertToWindowsCharset($string) {
      $encoding = mb_detect_encoding($string);
    
      return iconv($encoding, "Windows-1252", $string);
    }
    
    0 讨论(0)
  • 2020-11-22 06:15

    In my case following works very nice to make CSV file with UTF-8 chars displayed correctly in Excel.

    $out = fopen('php://output', 'w');
    fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
    fputcsv($out, $some_csv_strings);
    

    The 0xEF 0xBB 0xBF BOM header will let Excel know the correct encoding.

    0 讨论(0)
  • 2020-11-22 06:15

    Excel doesn't support UTF-8. You have to encode your UTF-8 text into UCS-2LE.

    mb_convert_encoding($output, 'UCS-2LE', 'UTF-8');
    
    0 讨论(0)
  • 2020-11-22 06:18

    This Post is quite old, but after hours of trying I want to share my solution … maybe it helps someone dealing with Excel and Mac and CSV and stumbles over this threat. I am generating a csv dynamically as output from a Database with Excel Users in mind. (UTF-8 with BOM)

    I tried a lot of iconv´s but couldn´t get german umlauts working in Mac Excel 2004. One solution: PHPExcel. It is great but for my project a bit too much. What works for me is creating the csv file and convert this csv file to xls with this PHPsnippet: csv2xls. the result xls works with excel german umlauts (ä,ö,Ü,...).

    0 讨论(0)
  • 2020-11-22 06:19

    Add:

    fprintf($file, chr(0xEF).chr(0xBB).chr(0xBF));
    

    Or:

    fprintf($file, "\xEF\xBB\xBF");
    

    Before writing any content to CSV file.

    Example:

    <?php
    $file = fopen( "file.csv", "w");
    fprintf( $file, "\xEF\xBB\xBF");
    fputcsv( $file, ["english", 122, "বাংলা"]);
    fclose($file);
    
    0 讨论(0)
提交回复
热议问题