【问题标题】:php insert text file to mysql encodingphp将文本文件插入mysql编码
【发布时间】:2013-05-05 03:45:25
【问题描述】:

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

当我用记事本打开 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Á

我哪里错了?

【问题讨论】:

    标签: php mysql phpmyadmin


    【解决方案1】:

    有几件事可能是错误的

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

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

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

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

    【讨论】:

    • 我尝试以下我从我的 txt 中回显第一个字母的 ord 并收到 208。在 iconv iconv('CP1253','UTF-8',$theData);我收到 206... 该怎么办?
    • 什么是正确的字符。应该是206还是208?当您尝试从数据库中获取此信息时(再次按顺序),您会得到什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 2013-09-01
    • 2012-10-15
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    相关资源
    最近更新 更多