2013-01-22 64 views
0

當我從MySQL.XLS文件傳輸數據時,我遇到了編碼問題。表格位於「utf8_czech_ci」和PHP腳本UTF-8。我總是會收到像「Äščřžýáíé」這樣的字符,像「ÄÄÄÄÄÅřžýÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃ」。還有就是我的腳本MySQL到.XLS編碼問題

<?php 

mb_http_input("utf-8"); 
mb_http_output("utf-8"); 

    $dbhost = "XXXXXXXXXXX"; 
    $dbuser = "XXXXXXXXXXX"; 
    $dbpass = "XXXXXXXXXXX"; 
    $dbname = "XXXXXXXXXXX"; 
    $dbtable = $_GET['table']; 

function xlsBOF() { 
    echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0); 
    return; 
} 

function xlsEOF() { 
    echo pack("ss", 0x0A, 0x00); 
    return; 
} 

function xlsWriteLabel($Row, $Col, $Value) { 
    $L = strlen($Value); 
    echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L); 
    echo $Value; 
    return; 
} 

$dbc = mysql_connect($dbhost , $dbuser , $dbpass) or die(mysql_error()); 
mysql_query("set names utf8;"); 
mysql_select_db($dbname); 
$q = "SELECT * FROM ".$dbtable.""; 
$qr = mysql_query($q) or die(mysql_error()); 

header("Pragma: public"); 
header("Expires: 0"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("Content-Type: application/force-download"); 
header("Content-Type: application/octet-stream"); 
header("Content-Type: application/download"); 
header("Content-type: application/vnd.ms-excel; charset=utf-8"); 
header("Content-Disposition: attachment;filename=export_".$dbtable.".xls "); 
header("Content-Transfer-Encoding: binary "); 
xlsBOF(); 

$col = 0; 
$row = 0; 
$first = true; 

while($qrow = mysql_fetch_assoc($qr)) 
{ 
    if($first) 
    { 
     foreach($qrow as $k => $v) 
     { 
      xlsWriteLabel($row, $col, strtoupper(ereg_replace("_" , " " , $k))); 
      $col++; 
     } 
     $col = 0; 
     $row++; 
     $first = false; 
    } 
    foreach($qrow as $k => $v) 
    { 
     xlsWriteLabel($row, $col, $v); 
     $col++; 
    } 

    $col = 0; 
    $row++; 
} 

xlsEOF(); 
exit(); 

感謝答覆...

+1

請不要將mysql_ *函數用於新代碼。它們不再被維護,並且[從PHP 5.5.0開始已棄用](http://php.net/manual/en/intro.mysql.php)。看到[紅色框](http://goo.gl/GPmFd)?相反,請了解[準備好的語句](http://goo.gl/vn8zQ)並使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/mysqli) 。如果您不能決定,[本文](http://goo.gl/3gqF9)將幫助您選擇。如果你想學習,這裏是很好的[PDO教程](http://goo.gl/vFWnC)。 – peterm

+1

你爲什麼要構建自己的BIFF文件?爲什麼不使用phpexcel? –

回答

0

一個Excel文件使用一個代碼頁塊,以確定被設定在文件中使用的字符,但默認情況下它會使用區域設置代碼頁。如果你想強制UTF-8,那麼你還需要編寫一個UTF-8代碼頁塊

$record   = 0x0042; // Record identifier 
$length   = 0x0002; // Number of bytes to follow 
$cv    = 0x04B0; // The UTF-8 code page 

$header   = pack('vv', $record, $length); 
$data   = pack('v', $cv);