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

2022-12-06 11:00:39 +08:00
 awanganddong

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
                }
1153 次点击
所在节点    程序员
12 条回复
awanganddong
2022-12-06 11:14:21 +08:00
这是相关联的帖子

https://www.v2ex.com/t/516880
awanganddong
2022-12-06 11:17:33 +08:00
对数据进行 print_r(bin2hex($test));
转码前后的值是一样的
20c2e0b162
20c2e0b162
ysc3839
2022-12-06 11:25:41 +08:00
发数据来看看?
IvanLi127
2022-12-06 11:32:26 +08:00
CP936 好像实现了 GB2312 + 部分 GBK ?
si
2022-12-06 11:39:19 +08:00
但是你这个代码不是应该 if ($typeofData == 'GBK') 吗
si
2022-12-06 11:50:14 +08:00
尴尬,测试了一下,确实是返回 CP936 。
转成 UTF-8 是
$val = mb_convert_encoding($val, 'UTF-8', $typeofData); //转成 UTF-8
awanganddong
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
2022-12-06 11:57:12 +08:00
可以通过编码检测工具对编码进行检测
si
2022-12-06 11:59:23 +08:00
@awanganddong CP936 就是 GBK ,GBK 和 BIG5 的编码范围重合,很容易会误判。
awanganddong
2022-12-06 12:04:29 +08:00
谢谢大家了
xuyang2
2022-12-06 15:23:23 +08:00
不要 **detect** encoding ,detect 实际上是**guess**
已知编码时直接用 mb_check_encoding mb_convert_encoding 就好了
awanganddong
2022-12-06 16:21:47 +08:00
@xuyang2 明白了,谢谢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/900437

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX