PHP uses fgetcsv to read CSV files appear garbled solution _php tips

Source: Internet
Author: User
Tags locale

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.