【发布时间】:2014-07-08 16:53:57
【问题描述】:
我遇到了特殊字符的问题,例如当我将 MySQL 查询导出到 CSV 文件时,俄语字符被转换为 ????。我使用了 iconv() 函数,但它不起作用。
我应该怎么做才能解决这个问题。我阅读了不同的帖子,但似乎没有什么对我有用
public function generateReport($nameReport,$db,$query,$host,$user,$pwd){
$con = mysql_connect($host,$user,$pwd);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db($db, $con);
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysql_error());
}
$res = mysql_query($query);
if (!$res) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
$file='/home/'.$nameReport.'.csv';
$fp = fopen($file,'w') or exit("Unable to open file!");
if($fp){
$row = mysql_fetch_assoc($res);
$line = "";
$comma = "";
foreach($row as $name => $value) {
$line .= $comma . '"' . str_replace('"', '""', $name) . '"';
$comma = ",";
}
$line .= "\n";
fputs($fp, $line);
mysql_data_seek($res, 0);
while($row = mysql_fetch_assoc($res)) {
$line = "";
$comma = "";
foreach($row as $value) {
iconv( mb_detect_encoding( $value ), 'UTF-8', $value);
$line .= $comma . '"' . str_replace('"', '""', $value) . '"';
$comma = ",";
}
$line .= "\n";
fputs($fp, $line);
}
}
return '/home/'.$nameReport.'.csv';
}
【问题讨论】:
-
这是遗留应用程序的一部分吗?我真的希望你不要用过时的
mysql_query接口编写新代码。 -
它只是写了一个可重用的函数。如果您有更好的建议,我可以更改它。
-
使用函数没有错。我要说的是
mysql_query是一个已弃用的接口,它已从 PHP 中删除,因此您应该尽可能避免使用它。
标签: php mysql utf-8 character-encoding