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

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

    For me none of the solution above worked. Below is what i did to resolve the issue: modify the value using this function in the PHP code:

    $value = utf8_encode($value);
    

    This output values properly in an excel sheet.

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

    #output a UTF-8 CSV in PHP that Excel will read properly.

    //Use tab as field separator   
    $sep  = "\t";  
    $eol  = "\n";    
    $fputcsv  =  count($headings) ? '"'. implode('"'.$sep.'"', $headings).'"'.$eol : '';
    
    0 讨论(0)
  • 2020-11-22 06:22

    I'm on Mac, in my case I just had to specify the separator with "sep=;\n" and encode the file in UTF-16LE like this:

    $data = "sep=;\n" .mb_convert_encoding($data, 'UTF-16LE', 'UTF-8');
    
    0 讨论(0)
  • 2020-11-22 06:24

    I have the same (or similar) problem.

    In my case, if I add a BOM to the output, it works:

    header('Content-Encoding: UTF-8');
    header('Content-type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename=Customers_Export.csv');
    echo "\xEF\xBB\xBF"; // UTF-8 BOM
    

    I believe this is a pretty ugly hack, but it worked for me, at least for Excel 2007 Windows. Not sure it'll work on Mac.

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

    I was having the same issue and it was solved like below:

        header('Content-Encoding: UTF-8');
        header('Content-Type: text/csv; charset=utf-8' );
        header(sprintf( 'Content-Disposition: attachment; filename=my-csv-%s.csv', date( 'dmY-His' ) ) );
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
    
        $df = fopen( 'php://output', 'w' );
    
        //This line is important:
        fputs( $df, "\xEF\xBB\xBF" ); // UTF-8 BOM !!!!!
    
        foreach ( $rows as $row ) {
            fputcsv( $df, $row );
        }
        fclose($df);
        exit();
    
    0 讨论(0)
  • 2020-11-22 06:24

    The CSV File musst include a Byte Order Mark.

    Or as suggested and workaround just echo it with the HTTP body

    0 讨论(0)
提交回复
热议问题