PHP Import CSV file encountered garbled problem Solution _php Tutorial

Source: Internet
Author: User
Tags field table locale locale setting
Today is mainly to write a PHP import CSV file method, in fact, a lot of online search. Can be implemented how to import. But I encountered two problems when importing, one is to write code on the windows when the test has garbled problem, and then resolved. The second is when it was submitted to the Linux system and it was garbled. I still don't know the reason is garbled, at first I thought it was the code SVN commit error, to the end I asked a question in one of my group, a friend is to do Phpcms, he said he encountered from the Windows submitted to Linux at the beginning of the error always occurred, Later, the reason for troubleshooting is garbled result. The following cut to see how to solve two problems!

Issue One solution:

PHP read the CSV file, in the windows on the Chinese language is not read, I immediately think of a function mb_convert_encoding (); set the following $str = Mb_convert_encoding ($str, "UTF-8", " GBK "); and then it's OK. Of course you can also use Iconv (), set Iconv (' GBK ', "Utf-8//translit//ignore", $str) as follows, and these two functions to solve the problem of garbled characters on Windows.

Problem two settlement:

PHP read CSV file, on Linux appear in the Chinese can not read the situation, Baidu, Google found a solution

is to add a line of code setlocale (Lc_all, ' zh_cn '); Yes, it's blinding your eyes. It's so simple, if you don't know, it might take a lot of time to solve the problem.
PHP setlocale () function explanation
Definition and usage

The setlocale () function sets the region information (geographic information).

Region information is the language, currency, time, and other information for a geographic region. The function returns the current locale setting and returns False if it fails.
The following is a collection of commonly used regional identifiers on the material:

Copy CodeThe code is as follows:
ZH_CN GB2312
en_US. UTF-8 UTF-8
ZH_TW BIG5
ZH_HK Big5-hkscs
Zh_tw. EUC-TW EUC-TW
Zh_tw. UTF-8 UTF-8
Zh_hk. UTF-8 UTF-8
Zh_cn. GBK GBK

For example
Utf-8: setlocale (Lc_all, ' en_US. utf-8′);
Notes: setlocale (lc_all, ' zh_cn ');

The reason to tell everyone setlocale () This function, because I import the CSV file to the Linux system when the garbled, including the use of mb_convert_encoding () and Iconv () two functions are not the final problem. Finally added this sentence setlocale (lc_all, ' zh_cn '); Add the code to the beginning of the import CSV file is easy to fix, and then I looked up the information, found that the fgetcsv () function is sensitive to the locale. Let's say LANG is set to en_US. UTF-8, a single-byte encoded file will have a read error, so we need to set it for culture. Special share to everyone.

I also tried to use the following code is not able to handle, these are generated CSV file header settings. It may not work here, but it might be in your place. So I have to sort out, as far as possible to help meet the import CSV file garbled counterparts, because in the case of no way is really too difficult to deal with. Everyone can try! There is always one that belongs to you.

Copy CodeThe code is as follows:
$csvContent = "Csvzero,csvone,csvtwo,csvthree,csvfour,csvfive";
Header ("Content-type:application/vnd.ms-excel; charset=gb2312 ");
Header ("Pragma:public");
Header ("expires:0");
Header ("Cache-control:must-revalidate, Post-check=0, pre-check=0");
Header ("Content-type:application/force-download");
Header ("Content-type:application/octet-stream");
Header ("Content-type:application/download");
Header ("Content-disposition:attachment;filename=csv data. csv");
Header ("Content-transfer-encoding:binary");
$csvContent = Iconv ("Utf-8", "gb2312", $csvContent);
Echo $csvContent;
Exit
?>

Here's a look at the code for the PHP import CSV file:

Two functions for a brief introduction,

The mb_detect_encoding () character encoding is detected, or false is returned if the encoding of the specified string cannot be detected.

The Fgetcsv () function reads a row from the file pointer and resolves the CSV field. Similar to Fgets (), the difference is that fgetcsv () parses a read-in row and finds a field in CSV format, and then returns an array containing those fields. Fgetcsv () returns FALSE when an error occurs, including when the file ends.

Note: from PHP 4.3.5, the operation of Fgetcsv () is binary safe.

Note: Empty rows in a CSV file are returned as an array containing a single null field and will not be treated as an error.

Note: This function is sensitive to locale settings. Let's say LANG is set to en_US. UTF-8, a single-byte encoded file will receive a read error.

Note: You can activate the Auto_detect_line_endings runtime configuration option if you encounter a line terminator for a Macintosh file that is not recognized by PHP when reading a file.
Copy CodeThe code is as follows:
SetLocale (Lc_all, ' zh_cn '); Set up region information (geo-information)
$file = $_files[' FILES '];
$file _type = substr (Strstr ($file [' name '], '. '), 1);
if ($file _type! = ' csv ') {
echo "";
Exit
}
$handle = fopen ($file [' Tmp_name '], "R");
$file _encoding = mb_detect_encoding ($handle);
if ($file _encoding! = ' ASCII ') {
echo "";
Exit
}
$row = 0;
$str = "";
$sy = "";
while ($data = Fgetcsv ($handle, 1000, ', ')) {
$row + +;
if ($row = = 0)
Continue
$num = count ($data);
for ($i =0; $i < $num; $i + +) {
$str = (string) $data [$i]. ' | ';
$str = mb_convert_encoding ($str, "UTF-8", "GBK"); Known source is GBK, converted to Utf-8
$sy. = $str; What I do here is more complicated, and it's a ' | ' Use the contents of the CSV file as ' | ' All together, because I import the product information, need to be based on user needs
The data to be imported to define which data needs to be imported.
}
}
if ($sy) {$sy = RTrim ($sy, ' | ');}
$arr = Explode (' | ', $sy);
$key = Array_slice ($arr, 0, $num); This array is the CSV file inside the title, is the product ID, title, selling points and so on data
$skey = Array ();
$length = Array ();
$co = count ($arr);
$p = $co/$num; Find out the length of the data to be fetched
for ($j =0; $j < $p; $j + +) {
$offset = ($J-1) * $NUM; Offset, just like paging, I'm going to take an array of offsets from here, which is the information for a commodity.
if ($j ==0) {
$length [] = Array_slice ($arr, 0, $num);
}else{
$length [] = Array_slice ($arr, $num + $offset, $num);//What fields and products are taken out
}
}
$arrtitle = Array ();
$arrfileds = Array ();
$arrtagname = Db::select (' Field id ', ' field name ')->from (' Field table ')->fetch_all ();
foreach ($arrtagname as $value) {
$arrfileds [$value [' fileds_tags ']] = $value [' Fileds_name '];
}
foreach ($fileds as $v)
{
$temarr = Explode ('-', $v);
if (isset ($temarr [0]) &&!empty ($temarr [0])) {
if (Isset ($temarr [1]) &&!empty ($temarr [1])) {
if ($temarr [1] = = ' Wenben ') {
$arrtitle [] = $arrfileds [$temarr [0]]. ' Text ';
}
} else {
if ($temarr [0]! = ' pic ') {//Is the Remove field is the picture to be removed
$arrtitle [] = $arrfileds [$temarr [0]];
}
}
}

}

$skey = Array ();
$order = Array ();
$order [] = ' act_tag ';
$order [] = ' channel_tag ';
$order [] = ' created_time ';
$order [] = ' by ';
$rows = ";
$f = $co/$num;//Find out how many items
for ($p =0; $p Here is to find out according to their own needs of the data, through the user needs of the Product field identification table corresponding to the English identity.
$skey []= db::select (' field ID ')->from (' Field table ')->where (' Field name ', ' = ', $arrtitle [$p])->fetch_row ();
$rows. = $skey [$p] [' Field ID ']. ' | ';
}
if ($rows) {$rows = RTrim ($rows, ' | ');}
if (!empty ($rows)) {$exrows = explode (' | ', $rows);} else{$exrows = Array ();}
$skeys = Array_merge ($order, $exrows);
$count 1 = count ($skeys); Number of fields
if (!empty ($length)) {
for ($x =1; $x < $f; $x + +) {//Find out how many pieces of goods are in the loop how many times
$orders = Array ();
$orders [] = $act _tag;
$orders [] = $channel _tag;
$orders [] = time ();
$newlen = Array_merge ($orders, $length [$x]);
if ($count 1!== count ($newlen)) {//If the length of the product field and the length of the product are not equal to prove which field the user has not entered
$newrs = Array ();
echo "";
Fclose ($handle);
Exit ();
}else{//start
$arrimport = Array_combine ($skeys, $newlen); If two arrays are equal I'll merge the array and change the date in the import CSV to a timestamp store to the database
if (!empty ($arrimport [' start_time '])) {$sta = Strtotime ($arrimport [' start_time ']);} else{$sta = (int) 0;}
if (!empty ($arrimport [' end_time '])) {$end = Strtotime ($arrimport [' end_time ']);} else{$end = (int) 0;}
$arrtime =array (' start_time ' = $sta, ' end_time ' and $end);
if (!empty ($arrimport [' start_time ']) &&!empty ($arrimport [' end_time ']) {
$newrs =array_merge ($arrimport, $arrtime);
}else{
$newrs = Array ();
echo "";
Fclose ($handle);
Exit ();
}
if (count ($skeys) = = count ($newrs)) {
Db::insert (' Commodity table ', Array_values ($skeys))
->values (Array_values ($newrs))
->execute ();
}
}//end
}
}
if ($row -1== (int) 0) {
echo "";
}else{
echo "

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.