0

我必须将数据从 .txt 文件导入到 mySQL 数据库。

当我用记事本打开 txt 文件时,文件是用 DOS/Windows ANSI 编写的(用 ANSI 编码)。当我用 AkelPad 打开它时,我得到文件以 1253(ANSI-Greek)编码的信息

我使用以下代码导入数据

$myFile = "Bill.txt";
$fh = fopen($myFile, 'r');
$theData1 = fread($fh, filesize($myFile));
$theData = str_replace("'","#",$theData1);
$theData = iconv('cp1253','UTF-8',$theData);
$data = (filesize($myFile))/156;
fclose($fh);
$line = 0;

mysql_query("TRUNCATE Bill");
for ($counter = 1; $counter <= $data; $counter++) {
  $Barcode[counter] = substr($theData, ($line+0), 10);
  $BuildingCode[counter] = substr($theData, ($line+10), 5);
  $BuildingAddress[counter] = substr($theData, ($line+14), 40);
  $FlatName[counter] = substr($theData, ($line+54), 50);
  $FlatDescription[counter] = substr($theData, ($line+104), 8);
  $EntrySeason[counter] = substr($theData, ($line+112), 23);
  $Period[counter] = substr($theData, ($line+135), 11);
  $Amountint = substr($theData, ($line+146), 7);
  $Amountdec = substr($theData, ($line+153), 2);
  $Amount[counter] = $Amountint.'.'.$Amountdec;

  mysql_query("INSERT INTO Bill (Id, Code, Address, Name, Description, EntrySeason, Period, Revenue) 
  VALUES ('$Barcode[counter]', '$BuildingCode[counter]', '$BuildingAddress[counter]', '$FlatName[counter]', '$FlatDescription[counter]', '$EntrySeason[counter]', '$Period[counter]', '$Amount[counter]')");

  $line = $counter * 156;
}

当我用代码读取上述数据时

$query = "SELECT * FROM Bill ORDER BY Id ASC"; 
$result = mysql_query($query) or die(mysql_error());
$i=0;
while ($row=mysql_fetch_array($result)){
$i=$i+1;
echo $i." - ".$row['Id']. " - ". $row['Code']. " - ". $row['Address']. " - ". $row['Name']. " - ". $row['Description']. " - ". $row['EntrySeason']. " - ". $row['Period']. " - ". $row['Revenue'].'<br>';

我收到希腊字母。当我用 phpmyadmin 检查 db 时,所有的希腊条目都是这样的字符ÃÅÙÑÃ.ÃÅÍÍÇÌÁÔÁ 39Á

如果我尝试将 mysql 中的条目插入到 sqlite 中,则字母是这些ÃÅÙÑÃ.ÃÅÍÍÇÌÁÔÁ 39Á

我哪里错了?

4

1 回答 1

0

有几件事可能是错误的

1)您确定您在尝试保存数据的数据库中使用的是 UTF-8 数据库、表、列吗?

2) 你运行 mysql_query("SET NAMES utf8"); 在对数据库运行选择/更新之前?

如果你都做对了,那么我建议你更详细地调试它。

3)尝试在txt文件中指定一个字符,并尝试在iconv函数前后回显ord($str{xxx}),检查二进制数据是否真的是UTF-8正确编码。

于 2013-05-10T13:19:26.433 回答