中国語を含むcsvとしてテーブルをエクスポートするというこの問題をちょっと解決しました。しかし、実際には phpmyadmin ではそうではありません。このエクスポート スクリプトを使用して、中国語を含む必要なテーブルをエクスポートすると、適切に表示されます。
<?php
/*
* PHP code to export MySQL data to CSV
* http://salman-w.blogspot.com/2009/07/export-mysql-data-to-csv-using-php.html
*
* Sends the result of a MySQL query as a CSV file for download
*/
/*
* establish database connection
*/
$conn = mysql_connect('MYSQL_HOST', 'MYSQL_USERNAME', 'MYSQL_PASSWORD') or die(mysql_error());
mysql_select_db('MYSQL_DATABASE', $conn) or die(mysql_error($conn));
mysql_query("SET character_set_results=utf8", $conn);
/*
* execute sql query
*/
$query = sprintf('SELECT * FROM MYSQL_TABLE');
$result = mysql_query($query, $conn) or die(mysql_error($conn));
/*
* send response headers to the browser
* following headers instruct the browser to treat the data as a csv file called export.csv
*/
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=export.csv');
echo "\xEF\xBB\xBF";
/*
* output header row (if atleast one row exists)
*/
$row = mysql_fetch_assoc($result);
if ($row) {
echocsv(array_keys($row));
}
/*
* output data rows (if atleast one row exists)
*/
while ($row) {
echocsv($row);
$row = mysql_fetch_assoc($result);
}
/*
* echo the input array as csv data maintaining consistency with most CSV implementations
* - uses double-quotes as enclosure when necessary
* - uses double double-quotes to escape double-quotes
* - uses CRLF as a line separator
*/
function echocsv($fields)
{
$separator = '';
foreach ($fields as $field) {
if (preg_match('/\\r|\\n|,|"/', $field)) {
$field = '"' . str_replace('"', '""', $field) . '"';
}
echo $separator . $field;
$separator = ',';
}
echo "\r\n";
}
?>
このコードは、次のソースからコピーおよび変更されました。
- http://salman-w.blogspot.hk/2009/07/export-mysql-data-to-csv-using-php.html
- CSV にエクスポートすると、ロシア語の文字が表示されない
問題はcsvファイルではなく、Excelにあることがわかりました。csv ファイルのエンコーディングに関係なく、Excel は常に ASCII としてファイルを開くため、中国語が台無しになります。上記のコードは
- csv を UTF-8 エンコーディングとしてエクスポートして、これで中国語を表示できるようにします
mysql_query("SET character_set_results=utf8", $conn);
- これでcsvをUTF-8として開くようにExcelに強制します
echo "\xEF\xBB\xBF";
これで問題は少し解決しますが、誰かがカスタム エクスポート スクリプトを必要とせずに phpmyadmin を介してこれを行う方法を理解できるとよいでしょう。