在PHP中导入带有亚洲字符的CSV [英] Importing CSV with Asian Characters in PHP

查看:46
本文介绍了在PHP中导入带有亚洲字符的CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将带有泰语字符的CSV或Unicode文本导入MySQL.MySQL保存泰语字符没有问题.问题是,当我使用fgetcsv或fgets时,会得到垃圾来换成泰语字符.像这些字符一样,ตู้เซฟเหล็ก变成9?I?@ ???? @ ???%?G.

I'm trying to import CSVs or Unicode Text with Thai Characters into MySQL. There's no problem with MySQL saving Thai Characters. The problem is, when I use fgetcsv or fgets, I get garbage in exchange for the Thai Characters. Like for example, these characters, ตู้เซฟเหล็ก becomes 9I@ @+%G.

我还有另一种方式可以读取CSV文件吗?也许可以正确读取它们的功能?

Is there another way I can read from CSV files? A function maybe that can read them correctly?

推荐答案

函数fgets和fgetcsv使用系统区域设置来进行有关字符编码的假设.我认为为此目的更改语言环境设置不是一个明确的解决方案.还有另一种方式.您只能使用utf-8,并将unicode明确转换为utf-8:

Functions fgets and fgetcsv uses the system locale setting to make assumptions about character encoding. In my opinion changing locale settings for that purpose isn't clear solution. There is another way. You can use only utf-8 and explicity convert unicode to utf-8:

示例代码(php> = 5.3):

Example code (php >= 5.3):

<?php
//set internal encoding to utf8
mb_internal_encoding('utf8');

$fileContent = file_get_contents('thai_unicode.csv');

//convert content from unicode to utf
$fileContentUtf = mb_convert_encoding($fileContent, 'utf8', 'unicode');

echo "parse utf8 string:\n";
var_dump(str_getcsv($fileContentUtf, ';'));

结果是:

php load.php
parse utf8 string:
array(2) {
  [0]=>
  string(36) "ตู้เซฟเหล็ก"
  [1]=>
  string(1) "1"
}

这篇关于在PHP中导入带有亚洲字符的CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆