How to troubleshoot PHP import CSV file encountered garbled problem

Source: Internet
Author: User
Tags field table locale setting rtrim
This article mainly introduces the PHP import CSV file encountered garbled problem resolution method, the need for friends can refer to the following

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:

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.

<?php $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.

<?php setlocale (lc_all, ' zh_cn '); Set up region information (geographic information) $file = $_files[' FILES '; $file _type = substr (Strstr ($file [' name '], '. '), 1); if ($file _type! = ' csv ') {echo "<script type=\" text/javascript\ ">alert (\" file format error, please re-upload!\ "); </script>"; Exit } $handle = fopen ($file [' Tmp_name '], "R"); $file _encoding = mb_detect_encoding ($handle); if ($file _encoding! = ' ASCII ') {echo "<script type=\" text/javascript\ ">alert (\" File encoding error, please re-upload!\ "); </script > "; Exit } $row = 0; $str = ""; $sy = ""; while ($data = Fgetcsv ($handle, +, ', ')) {$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; It's more complicated to use ' | ' Use the contents of the CSV file as ' | ' Put it all together, because I am importing commodity information and need to define what data needs to be imported according to the data that the user needs//to import. }} 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 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 as a product. if ($j ==0) {$length [] = Array_slice ($arr, 0, $num);} else{$length [] = Array_slice ($arr, $num + $offset, $num);//Check out what fields and goods}} $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 to remove the 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 goods for ($p =0; $p <count ($arrtitle); $p + +) {//here is based onTheir needs to identify 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); The number of fields if (!empty ($length)) {for ($x =1; $x < $f; $x + +) {//To find out how many cycles $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 commodity field and the length of the product are not equal to prove which field the user has not entered $newrs = Array (); echo "<script type=\" text/ Javascript\ ">alert (\" <font color= #f00;> ". Please check the section, '. ($x-1). ' Items! '.' Import failed! '." </font> "); </script> "; Fclose ($handle); Exit (); }else{//start $arrimport = Array_combine ($skeys, $newlen);//If two arrays are equal I will merge the array and change the date inside 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 ' = $end); if (!empty ($arrimport [' start_time ']) &&!empty ($arrimport [' end_time ']) {$newrs =array_merge ($arrimport, $ Arrtime); }else{$newrs = Array (), echo "<script type=\" text/javascript\ ">alert (\" <font color= #f00;> ". Please check the section, '. ($x-1). ' Items! '.' Import failed! '." </font> "); </script> "; 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 "<script type=\" text/javascript\ ">alert (\" <font color= #f00;> ". The item you imported is empty! '." </font> "); </script> "; }else{echo "<script type=\" text/javascript\ ">alert (\" <font color= #f00;> ". Successfully imported '. ' <font color= #f00;> ". ($row-1). " </font> '. ' Items! '." </font> "); } fclose ($handle); }?>

The above is my work need to do the CSV import processing, and you may import different ways, but some of the code will always help you!

The following is a simple import:

<form enctype= "Multipart/form-data" action= "import.php" method= "POST" > Import template <label for= "File Selection" > File selection: </ Label><input name= "csv_goods" type= "file"/> <input type= "Submit" value= "import" name= ' Import '/> </form& Gt <?php if (isset ($_post[' import '))) {$file = $_files[' csv_goods ']; $file _type = substr (Strstr ($file [' name '], '. '), 1); Check the file format if ($file _type! = ' csv ') {echo ' file format is incorrect, please re-upload! '; exit;} $handle = fopen ($file [' Tmp_name '], "R"); $file _encoding = mb_detect_encoding ($handle); Check the file encoding if ($file _encoding! = ' ASCII ') {echo ' File encoding error, please re-upload! '; exit;} $row = 0; while ($data = Fgetcsv ($handle, +, ', ')) {//echo "<font color=red> $row </font>";//You can know how many lines $row + +; row = = 1) continue; $num = count ($data); In turn, the data for each cell in each row is output for ($i =0; $i < $num; $i + +) {echo $data [$i]. " <br> "; Processing the data Here}} fclose ($handle); }?>

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

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.