V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
awanganddong
V2EX  ›  程序员

csv 中繁体汉字导入数据库乱码

  •  
  •   awanganddong · 2022-12-06 11:00:39 +08:00 · 1146 次点击
    这是一个创建于 504 天前的主题,其中的信息可能已经有所发展或是发生改变。

    csv 里边繁体汉字的格式是 CP936 ,相当于是 gbk 的别称。 然后通过下边两个函数均无效。 所以想知道问题出在哪里?

             $typeofData = mb_detect_encoding($val, array("GBK", "GB2312", "UTF-8", "ASCII", "BIG5"));
                    if ($typeofData == 'CP936') {
    //                    $val = @iconv("GBK", "UTF-8//TRANSLIT//IGNORE", $val);
                        $val = mb_convert_encoding($val, 'GBK', $typeofData); //转成 UTF-8
                    }
    
    12 条回复    2022-12-06 16:21:47 +08:00
    awanganddong
        1
    awanganddong  
    OP
       2022-12-06 11:14:21 +08:00
    这是相关联的帖子

    https://www.v2ex.com/t/516880
    awanganddong
        2
    awanganddong  
    OP
       2022-12-06 11:17:33 +08:00
    对数据进行 print_r(bin2hex($test));
    转码前后的值是一样的
    20c2e0b162
    20c2e0b162
    ysc3839
        3
    ysc3839  
       2022-12-06 11:25:41 +08:00
    发数据来看看?
    IvanLi127
        4
    IvanLi127  
       2022-12-06 11:32:26 +08:00
    CP936 好像实现了 GB2312 + 部分 GBK ?
    si
        5
    si  
       2022-12-06 11:39:19 +08:00
    但是你这个代码不是应该 if ($typeofData == 'GBK') 吗
    si
        6
    si  
       2022-12-06 11:50:14 +08:00
    尴尬,测试了一下,确实是返回 CP936 。
    转成 UTF-8 是
    $val = mb_convert_encoding($val, 'UTF-8', $typeofData); //转成 UTF-8
    awanganddong
        7
    awanganddong  
    OP
       2022-12-06 11:53:49 +08:00
    我上传的 csv 文件是 big5 类型的,用这个就可以解决。
    $val = @iconv("Big5", "UTF-8//TRANSLIT//IGNORE", $val);

    问题在于怎么识别出文件真实类型,
    $typeofData = mb_detect_encoding($val, array("GBK", "GB2312", "UTF-8", "ASCII", "BIG5"));
    我打印出来的就是 CP936 ,这个就很困惑了
    awanganddong
        8
    awanganddong  
    OP
       2022-12-06 11:57:12 +08:00
    可以通过编码检测工具对编码进行检测
    si
        9
    si  
       2022-12-06 11:59:23 +08:00
    @awanganddong CP936 就是 GBK ,GBK 和 BIG5 的编码范围重合,很容易会误判。
    awanganddong
        10
    awanganddong  
    OP
       2022-12-06 12:04:29 +08:00
    谢谢大家了
    xuyang2
        11
    xuyang2  
       2022-12-06 15:23:23 +08:00
    不要 **detect** encoding ,detect 实际上是**guess**
    已知编码时直接用 mb_check_encoding mb_convert_encoding 就好了
    awanganddong
        12
    awanganddong  
    OP
       2022-12-06 16:21:47 +08:00
    @xuyang2 明白了,谢谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5307 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 09:25 · PVG 17:25 · LAX 02:25 · JFK 05:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.