我正在开发一个脚本,它将csv作为输入,然后读取文件并将其内容插入到mysql数据库中。所以在将数据插入数据库时出现问题。它将UMLAUT转换为随机字符。使用php脚本将UMLAUT插入mysql数据库
仅供参考 - 我的数据库在latin_german_ci。 [我也尝试将其更改为UTF8]
我能够在Web浏览器中显示UMLAUT字符,但是当我尝试通过sql查询将它们插入到数据库中时,它会插入随机字符。
<?php
function uploadCsv($filename){
echo "filename - ".$filename."<br/>";
if(isset($filename) || $filename == ""){ // return with an error msg.
}else{
$pos = stripos($filename, ".csv");
if($pos == 0 || $pos != strlen($filename)-4){
//echo "invalid format";
return ;
}
}
set_time_limit(0);
$error = "";
$row = 0;
$handle = fopen($filename, "r");
//echo "<br/>".$filename."<br/>";
//echo "<br/>".$handle."<br/>";
if($handle == null){
return "unable to process";
}
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
if ($row == 0) {
// this is the first line of the csv file
// it usually contains titles of columns
// do nothing.
$num = count($data);
//echo "num - ".$num."<br/>";
if($num != 2){
// echo "returning back";
return "invalid CSV format.";
}
}
// this handles the rest of the lines of the csv file
$num = count($data);
$id = $data[0];
$inserQuery = "";
$inserQuery = "INSERT INTO `table` (
`ID` ,
`Productname`
)
VALUES (";
for ($c=0; $c < $num; $c++) {
if($c==0){
$inserQuery .= " '". utf8_encode($data[$c])."'" ;
}else{
$inserQuery .= ", '". utf8_encode($data[$c]) ."'" ;
}
}
$inserQuery .= ");";
echo $inserQuery."<br/>";
mysql_query($inserQuery);
if(mysql_affected_rows() == -1 || mysql_affected_rows() <1){
echo "error<br/>";
}else{
echo "row inserted - ".$row." with ID = ".$id." <br/>";
}
$row++;
}
fclose($handle);
return "1";
}
?>
请帮助....
感谢
而且您应该检查CSV文件的编码和您的区域设置以及...因为fgetcsv的PHP手册指出:*注意:此功能考虑了区域设置。如果LANG是例如en_US.UTF-8,单字节编码的文件被这个函数读错了。* – wimvds 2010-05-20 15:35:19
如何在Windows上更改CSV文件的区域设置? – mudit 2010-05-25 10:22:09
取决于您创建CSV的程序,例如使用Excel,你会被默认的字符集卡住(至少据我所知)。 – 2010-05-25 10:34:24