【问题标题】:php export mysql chinese character to csv, but the character becomes garbage codephp导出mysql汉字到csv,但是字符变成垃圾码
【发布时间】:2016-04-04 07:05:37
【问题描述】:

我正在尝试将数据从 mysql 导出到包含一些汉字的 csv,但是它总是变成垃圾代码。我用谷歌搜索并找到在标题处添加 BOM 的建议。但它似乎仍然不起作用,这是我的代码。请提出建议。

<?php
if(isset($_POST["Export"]))
{   
mysql_connect('localhost','test','abc');
mysql_select_db('test');

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');

$data = fopen( 'php://output', 'w' );

//This line is important:
fputs( $data, "\xEF\xBB\xBF");

fputcsv($data,array('student_id','student_chiName','student_engName','    student_title','student_gender','news_receive'));


//Retrieve the data from database
$rows = mysql_query('SELECT * FROM student');

//Loop through the data to store them inside CSV
while($row = mysql_fetch_assoc($rows)){
fputcsv($data, $row);

}
}

?>

这是我的十六进制视图,似乎汉字只有一个字节,缺少一个字节。似乎 PHP 没有以 4 个字节输出字符。

【问题讨论】:

    标签: php mysql csv export


    【解决方案1】:

    试试这个:

    $data = fopen($filepath, 'w');
    $rows = mysql_query('SELECT * FROM student');
    
    fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF));
    while($row = mysql_fetch_assoc($rows)){
        fputcsv($data, $row);
    }
    

    fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF)); 行写入文件头以进行正确编码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-21
      • 2015-05-18
      • 1970-01-01
      • 1970-01-01
      • 2013-02-07
      • 2010-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多