2016-04-04 15 views
0

我想從mysql導出數據到包含一些中文字符的csv,但它總是變成垃圾代碼。我搜索了一下,並在標題中找到了添加BOM的建議。但它似乎仍然不起作用,這裏是我的代碼。請建議。PHP將mysql中文字符導出爲csv,但該字符變成垃圾代碼

<?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個字節的字符。 The hex dump of output file by PHP

回答

0

試試這個:

$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));正確編碼寫入文件頭。