This article is an example of how PHP uses Fgetcsv to read CSV files with garbled solutions. Share to everyone for your reference. The specific analysis is as follows:
In general, in PHP encountered garbled most of the coding problem, here we case analysis of Fgetcsv read CSV file garbled reason and solution.
Examples are as follows:
Copy Code code as follows:
function get_csv_contents ($file _target) {
$handle = fopen ($file _target, ' R ');
while ($data = Fgetcsv ($handle, 1000, ",")) {
$num = count ($data);
echo "<p> $num fields in line $row: <br>n";
$row + +;
for ($c =0; $c < $num; $c + +) {
echo $data [$c]. "<br>n";;
/*echo getutfstring ($data [$c]) * *
}
}
Fclose ($handle);
}
Imported CSV file is saved in ANSI encoding, for the Chinese operating system environment should be GBK encoding, by manually changing the browser character encoding for GBK, garbled situation disappeared, in the following adjustments.
Copy Code code as follows:
$data = eval (' Return '. Iconv (' GBK ', ' Utf-8 ', Var_export ($data, True)).
$data is an array that requires conversion encoding.
Add: LINUX fgetcsv read GBK data garbled
When the Linux system is used by the default settings, the Linux server on the GBK CSV format file processing, there will be garbled phenomenon.
The solution is:
Use the setlocale function to set environment variables. For example, to set a locale that uses GB, you can use the following statement before Fgetcsv.
Copy Code code as follows:
SetLocale (Lc_all,array (' zh_cn.gbk ', ' zh_cn.gb2312 ', ' zh_cn.gb18030 '));
Which locale you use to use the Linux command locale-a to see what the system supports
I hope this article will help you with your PHP program design.