PHP Import CSV file encountered garbled problem solving method

Source: Internet
Author: User
Tags foreach explode field table locale rtrim

  This article mainly introduces the PHP import CSV file encountered garbled problem solution, 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 I import, one is to write code on Windows when the test has garbled problems, and then resolved. The second is to submit to the Linux system when there is garbled. I don't know why it's garbled at first, at first I thought it was the code SVN commit error, in the end I asked a question in one of my group, a friend is doing phpcms, he said he encountered from Windows submitted to Linux at the beginning also always error, Then the reason for the investigation is garbled result. Below cut to the point to see how to solve two problems!     Problem One solution:    PHP read csv file, in the windows of Chinese read the situation, I immediately think of a function mb_convert_encoding (); set the following $str = Mb_ Convert_encoding ($str, "UTF-8", "GBK"); Of course you can also use Iconv () to set the following iconv (' GBK ', ' Utf-8//translit//ignore ', $str); These two functions solve the problem of garbled characters on Windows.     Problem II solution:    PHP read csv file, on Linux, there is no read in Chinese, Baidu, Google found after the solution     is added a line of code setlocale (lc_ All, ' zh_cn '); Yes, blind your eyes. As simple as that, if you don't know it, it may take a long time to solve the problem.   PHP setlocale () function explanation   definition and usage     setlocale () function to set up area information (geographic information).     Area information is for the language, currency, time, and other information for a geographic region. The function returns the current locale and false if it fails.   Below is the collection of commonly used area identification:  code as follows: ZH_CN gb2312  en_US. UTF-8 utf-8  zh_tw big5  zh_hk big5-hkscs . 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′);  simplified: setlocale (lc_all, ' zh_cn ');    told everyone setlocale () This function, because I import a CSV file to the Linux system when there is garbled, These include the mb_convert_encoding () and Iconv () two functions that do not fix the final problem. Finally add this sentence setlocale (lc_all, ' zh_cn '); Add the code to the beginning of the import CSV file, and then I find the data and find that the Fgetcsv () function is sensitive to the locale. For example, LANG is set to en_US. UTF-8, a single byte-encoded file can have a read error, so we need to set it to culture. Special share to everyone.     I also tried to use the following code also failed to do, these are the generation of CSV file header settings. It may not work for me, but it might be in your place. So I sorted out, as far as possible to help encounter import CSV file garbled peers, because in the case of no way is really too difficult to deal with. We can all try! There is always one that belongs to you.     Code as follows: <?php  $csvContent = "Csvzero,csvone,csvtwo,csvthree,csvfour,csvfive";  header (" Content-type:application/; 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; ?>    The following is a concrete look at the code for PHP import CSV file:    Two functions a brief introduction,    mb_detect_ Encoding () The character encoding detected, or false when the encoding of the specified string cannot be detected. The     Fgetcsv () function reads a row from the file pointer and resolves the CSV field. Like Fgets (), the difference is that the fgetcsv () resolves the read rows and finds the CSV-formatted fields, and then returns an array containing the fields. Fgetcsv () returns FALSE when an error occurs, including when the end of the file is encountered.     notes: from PHP 4.3.5, the Fgetcsv () operation is binary safe.     NOTE: The empty row in the CSV file is returned as an array containing a single null field and is not treated as an error.     NOTE: This function is sensitive to locale settings. For example, LANG is set to en_US. UTF-8, a single byte-encoded file can have a read error.     NOTE: If you encounter a line terminator in which PHP does not recognize the Macintosh file while reading the file, you can activate the auto_detect_line_endings run-time configuration option.   Copy code code as follows: <?php  setlocale (lc_all, ' zh_cn '); Set Regional information (geographic information)   $file = $_files[' FILES '];  $file _type = substr (Strstr ($file [' name '], '. '), 1);  if ($file _type!= ' csv ') {  Echo <Script type= "Text/javascript" >alert ("file is malformed, please upload it again!"); </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 upload again! "); </script> ";  exit; }  $row = 0;  $str =" ";  $sy =" ";  while ($data = Fgetcsv ($handle, 1 , ', ') {  $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'm doing here is more complicated, with ' | ' Use the contents of the CSV file with ' | ' All together, because I am importing merchandise information, need to be based on user needs  //To import the data to define which data is to be imported.  } }  if ($sy) {$sy = RTrim ($sy, ' | ');}   $arr = explode (' | ', $sy);  $key = array_slice ($arr, 0, $num); This array is the title of the CSV file, which is the product ID, title, selling point, etc. 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, an array I take out based on offsets is information about a product.   if ($j ==0) {  $length [] = Array_slice ($arr, 0, $num); }else{  $length [] = Array_slice ($arr, $num +$ Offset, $num); What fields and products are removed  } }  $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 taken out of the picture to remove   $arrtitle [] = $arrfileds [$temarr [0]];&NB Sp } } }   }    $skey = array();  $order = Array ();  $order [] = ' Act_tag ';  $order [] = ' Channel_tag ';  $order [] = ' created_time '; &n Bsp $order [] = ' ORDER BY ';  $rows = ';  $f = $co/$num; How many items are available   for ($p =0; $p <count ($arrtitle); $p + +) {  //Here is according to their own needs to find their own needs of data, through the user needs of the commodity field identification of the corresponding English identification table.   $skey []= db::select (' field ID ')->from (' Field table ')->where (' Field name ', ' = ', $arrtitle [$p])->fetch_row ();  $ Rows. = $skey [$p] [' field identification ']. ' | '  }  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 items on the loop how many times   $orders = Array ();  $ orders[] = $act _tag;  $orders [] = $channel _tag;  $orders [] = time ();  $newlen = Array_merge ($orders, $lengt h[$x]);  if ($count 1!== count ($newlen)) {//If the length of the commodity field and the length of the product show that the user has not entered the field   $newrs = Array ();  ECHo "<script type=" Text/javascript >alert ("<font color= #f00;>". Please check the first, '. ($x-1). ' Piece of merchandise! '.' Import failed! '." </font> "); </script> ";  fclose ($handle);  exit (); }else{//start  $arrimport = Array_combine ($skeys, $ Newlen); If two arrays are equal I merge the array and change the date in the import CSV to the 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 first, '. ($x-1). ' Piece of merchandise! '.' Import failed! '." </font> "); </script> ";  fclose ($handle);  exit (); }  if (count ($skeys) = = count ($newrs)) {  DB:: Insert (' Commodity list ', Array_values ($skeys))  ->values (Array_values ($newrs))  ->execute (); } }//end }  }  if ($row -1== (int) 0) {  echo "<script type=" Text/javascript ">alert (" <font color= #f00;> " .' The product you imported is empty! '." </font> "); </script> "; }else{  echo" <script type= "Text/javascript" >alert ("<font color= #f00;>". ' Successfully imported '. ' <font color= #f00;> ". ($row-1). " </font> ". ' Piece of merchandise! '." </font> "); }  fclose ($handle); } ?>    Above is what I need to do in the CSV import processing, may be different from the way you import, But some of the code will always help you!   Below is a simple import:  copy code code as follows: <form enctype= "Multipart/form-data" action= "import.php" method= "POST" >  Import templates   <label for= "File Selection" > File selection: </label><input name= "csv_goods" type= "file"/>  Type= "Submit" value= "Imports" name= "import"/>  </form>  <?php  if (isset ($_post[' import ')) {     $file = $_files[' csv_goods '];    $file _type = substr (Strstr ($file[' name ', '. '), 1;   //Check file format   if ($file _type!= ' csv ') {  echo ' file is not in the correct format, please upload it again! ';   exit; }  $handle = fopen ($file [' Tmp_name '], "R");  $file _encoding = mb_detect_encoding ($handle);    /Check file encoding   if ($file _encoding!= ' ASCII ') {  echo ' File encoding error, please upload it again! '   exit; }    $row = 0;  while ($data = Fgetcsv ($handle, 1000, ', ')) { //echo "<font red> $row </font> "; You can tell how many rows   $row ++;  if ($row = = 1)   continue;  $num = count ($data); //And this will sequentially output each cell in each row &N Bsp For ($i =0 $i < $num $i + +) {  echo $data [$i]. " <br> "; //Data processing here  } }    fclose ($handle); }   ?>   
Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.