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

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

    I use this and it works

    header('Content-Description: File Transfer');
    header('Content-Type: text/csv; charset=UTF-16LE');
    header('Content-Disposition: attachment; filename=file.csv');
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    // output headers so that the file is downloaded rather than displayed
    // create a file pointer connected to the output stream
    $output = fopen('php://output', 'w');
    fputs( $output, "\xEF\xBB\xBF" );
    // output the column headings
    fputcsv($output, array('Thông tin khách hàng đăng ký'));
    // fetch the data
    $setutf8 = "SET NAMES utf8";
    $q = $conn->query($setutf8);
    $setutf8c = "SET character_set_results = 'utf8', character_set_client =
    'utf8', character_set_connection = 'utf8', character_set_database = 'utf8',
    character_set_server = 'utf8'";
    $qc = $conn->query($setutf8c);
    $setutf9 = "SET CHARACTER SET utf8";
    $q1 = $conn->query($setutf9);
    $setutf7 = "SET COLLATION_CONNECTION = 'utf8_general_ci'";
    $q2 = $conn->query($setutf7);
    $sql = "SELECT id, name, email FROM myguests";
    $rows = $conn->query($sql);
    $arr1= array();
    if ($rows->num_rows > 0) {
    // output data of each row
    while($row = $rows->fetch_assoc()) {
        $rcontent = " Name: " . $row["name"]. " - Email: " . $row["email"];  
        $arr1[]["title"] =  $rcontent;
    }
    } else {
         echo "0 results";
    }
    $conn->close();
    // loop over the rows, outputting them
    foreach($arr1 as $result1):
       fputcsv($output, $result1);
    endforeach;
    

提交回复
热议问题