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

后端 未结 30 3026
半阙折子戏
半阙折子戏 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: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();
    

提交回复
热议问题