Alb*_*ana 2 php mysql csv character-encoding export-to-csv
我有这个代码,我用它来导出一个CSV查询,问题是,如果我用Excel打开这个俄语字符将不会显示,但如果我打开它与数字(Mac)他们显示.
现在,我无法解决这个问题.我添加了一些我在互联网上看到的线条而没有...
<?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('', '', '') or die(mysql_error());
mysql_select_db('', $conn) or die(mysql_error($conn));
mysql_query("SET NAMES UTF8");
/*
* execute sql query
*/
$query = sprintf('SELECT fields FROM 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; charset=utf-8');
header('Content-Disposition: attachment;filename=hostess.csv');
/*
* 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";
}
?>
Run Code Online (Sandbox Code Playgroud)
该脚本不是为UTF-8编码数据创建的.它几乎按原样转储数据.生成的CSV文件将包含(可能)有效的UTF-8编码数据,但不包含签名.在没有签名的情况下,某些软件会使用启发式方法来检测编码; 其他人,比如Excel,不会.
您必须告诉excel将文件视为UTF-8编码.为此,您需要在Excel中导入文件(数据>获取外部数据>从文本)而不是直接打开它(双击或使用文件>打开).在文本导入向导中,选择适当的编码,Excel应正确导入数据.请参阅下面的截图.
// ...
header('Content-Disposition: attachment;filename=hostess.csv');
echo "\xEF\xBB\xBF";
// ...
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
10516 次 |
| 最近记录: |