0

我在将数据从MySQL传输到.XLS文件时遇到了编码问题。表在“ utf8_czech_ci ”和UTF-8中的PHP脚本中。我总是得到像“ěščřžýáíé”这样的坏字符,比如“ěšÄřžýáÃé”。有我的剧本

<?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();

感谢您的回复...

4

1 回答 1

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);
于 2013-02-14T07:37:34.577 回答