首页 > 解决方案 > 在真实主机上使用 UTF-8 将表数据导出到 CSV 文件

问题描述

我尝试将数据从 MySQL 表导出到 CSV 文件,它适用于我的虚拟主机但是当我在真实主机上上传它时,导出有 UTF-8 的问题,我使用下面的代码

require_once 'config.php';
$questions = questions::getAssoc("SELECT id,question FROM question");
download_csv_results($questions, 'file.csv');
exit();
function download_csv_results($questions , $name)
{
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    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');
    echo "\xEF\xBB\xBF"; // UTF-8 BOM
    $outstream = fopen("php://output", "wb");
    fputcsv($outstream, array_keys($questions[0]));

    foreach($questions as $question)
    {
        $id = $question['id'];
        fputcsv($outstream, $question);
        $answers = answers::getAssoc("SELECT name,answer,mobile FROM answer WHERE qid=$id");
        foreach ($answers as $answer){
            fputcsv($outstream, $answer);
        }
    }

    fclose($outstream);
}

在虚拟主机上

在真实主机上

标签: phpmysqlcsv

解决方案


推荐阅读