2017-10-10 78 views
4

我正在从文件中读取JSON字符串,解析它,然后将数据插入MySQL数据库。我插入查询抛出以下错误:文件读取到数据库插入导致unicode字符串

SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xE3\xADs' for column 'fname' at row 1 

我相信导致错误的内容是在名称Ailís(我呼应的ID,直到错误被抛出)的í

  • 该文件是UTF8使用UTF8上下文
  • 我检查的数据的编码是UTF8(它是)
  • 我的PDO连接具有UTF8编码
  • 我读该文件字符集,以及SET NAMES utf8
  • 该数据库是UTF8编码
  • 该表是UTF8编码
  • 列是UTF8编码

代码:

$opts = ['http' => ['header' => 'Accept-Charset: UTF-8, *;q=0']]; 
$context = stream_context_create($opts); 
$post = file_get_contents('sample_data/11111a_json_upload.json',false, $context); 
if(!mb_check_encoding($post, 'UTF-8')) 
    throw new Exception('Invalid encoding detected.'); 
$data = json_decode($post, true); 

我还插入下面的函数之前,我解码的JSON:

static function clean_unicode_literals($string) 
{ 
    return preg_replace_callback('@\\\(x)?([0-9a-zA-Z]{2,3})@', 
     function ($m) { 
      if ($m[1]) { 
       $hex = substr($m[2], 0, 2); 
       $unhex = chr(hexdec($hex)); 
       if (strlen($m[2]) > 2) { 
        $unhex .= substr($m[2], 2); 
       } 
       return $unhex; 
      } else { 
       return chr(octdec($m[2])); 
      } 
     }, $string); 
} 

当我读到的原始文件,当我解析的数据回显到浏览器,名称显示正确。因此,我认为这个问题与我有关?

我创建了一个新的PDO实例,像这样:

public function __construct($db_user, $db_pass, $db_name, $db_host, $charset) 
{ 
    if(!is_null($db_name)) 
     $dsn = 'mysql:host=' . $db_host . ';dbname=' . $db_name . ';charset=' . $charset; 
    else 
     $dsn = 'mysql:host=' . $db_host . ';charset=' . $charset; 

    $options = [ 
     PDO::ATTR_PERSISTENT => true, 
     PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 
     PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'" 
    ]; 

    try 
    { 
     $this->db_handler = new PDO($dsn, $db_user, $db_pass, $options); 
     $this->db_handler->exec('SET NAMES utf8'); 
     $this->db_valid = true; 
    } 
    catch(PDOException $e) 
    { 
     $this->db_error = $e->getMessage(); 
     $this->db_valid = false; 
    } 

    return $this->db_valid; 
} 

(SET NAMES有两次我排除故障......)
数据库,表和列字符集设置为utf8_general_ci

我的IDE是PHPStorm,而我在Windows上运行WAMP的MySQL 5.7.14 10

+0

那么实际上插入的代码在哪里? – Sammitch

回答

1

东西肯定是不对的输入字符串:\xE3\xADs

的前半部分E表明,它应该是一个3字节的UTF-8序列,但只有两个字节。

而且它绝对不是í,因为这是双字节序列\xC3\xAD

我不得不想知道为什么你有那个clean_unicode_literals函数,因为根据JSON规范,所有JSON字符串和文档都应该是有效的UTF-8。

尝试删除clean_unicode_literals调用,并且如果您仍然收到错误,那么源数据已损坏。