Importing CSV with Asian Characters in PHP [closed]

余生长醉 提交于 2021-01-28 05:08:50

问题


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.

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


回答1:


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:

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, ';'));

and the result is:

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


来源:https://stackoverflow.com/questions/19474031/importing-csv-with-asian-characters-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!