php import csv file encountered a solution to the garbled code problem

  • 2020-12-26 05:35:54
  • OfStack

Today I mainly want to write a method of php import csv file, in fact, 1 search on the Internet 1 a lot. You can implement how to import. However, I encountered two problems when Importing it. The first problem was that when I was writing code on windows, I had a messy code problem in the test, and it was solved. The second is that the submission to the linux system was messy again. At first, I didn't know the reason for the disorderly code. At first, I thought it was the error caused by the code svn submission. At last, I asked a question in one of my groups. Now cut to the chase to see how to solve two problems!

Problem 1 Solved:

php reads the csv file. If the Chinese version cannot be read on windows, I immediately think of a function mb_convert_encoding(). Set $str = mb_convert_encoding($str, "ES23en-8 ", "GBK"); And then you're done. You can also use iconv(); Set iconv(' GBK', "UTF-8//TRANSLIT//IGNORE",$str) as follows; These two functions solve the problem of garbled code on windows.

Problem 2 Solved:

php reads the csv file, but the Chinese version cannot be read on linux. After Baidu google, it finds a solution

Just add 1 line setlocale(LC_ALL, 'zh_CN'); Yeah, you're blind. It's as simple as that, and if you don't know, you'll probably spend a lot of time working on it.
PHP setlocale() function interpretation
Definition and usage

The setlocale() function sets locale information (locale information).

Regional information is language, currency, time, and other information for a geographic area. This function returns the current locale or false on failure.
The following are commonly used area labels for data collection:

 
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');
Simplified Chinese: setlocale(LC_ALL, 'zh_CN');

The reason why I'm telling you about setlocale() is that there was some confusion when I imported the csv file into the linux system, including the use of mb_convert_encoding() and iconv(), both of which did not solve the final problem. The last sentence is setlocale(LC_ALL, 'zh_CN'); This was easily done by adding the code at the beginning of importing the csv file, and then I looked at the data again and found that the fgetcsv() function is locale-sensitive. For example, if LANG is set to ES94en_US.UTF-8, the single-byte encoded file will get read errors, so we need to set it to the culture. I'd like to share with you.

I also tried and failed with the following code, which is the setup for header to generate csv files. It may not work for me, but it may not work for you. Therefore, I sorted them out and tried my best to help the peers who imported the messy code of csv files, because it was really difficult to deal with in the case of no way. Everyone can try! There will always be one for 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 is the code to import csv files:

I'm going to introduce you to two functions briefly 1,

mb_detect_encoding() returns FALSE if it detects a character encoding, or if it cannot detect the encoding of the specified string.

The fgetcsv() function reads 1 line from the file pointer and parses the CSV field. Similar to fgets(), the difference is that fgetcsv() parses the rows read in and finds the fields in CSV format, then returns an array containing those fields. fgetcsv() returns FALSE in case of an error, including when the end of the file is encountered.

Note: As of PHP 4.3.5, fgetcsv() operates in base 2 safety.

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

Note: This function is locale-sensitive. For example, if LANG is set to ES136en_US.UTF-8, the single-byte encoded file will get a read error.

Note: You can activate the auto_detect_line_endings runtime configuration option if PHP does not recognize the line end of the Macintosh file when reading the file.
 
<?php 
setlocale(LC_ALL, 'zh_CN'); // Setting up local information (regional 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,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 code is GBK Converting, utf-8 
$sy .= $str; // I'm going to make it a little bit more complicated here '|' will csv The contents of the file are used '|' Put it all together , Because what I import is the commodity information, which needs to be based on the user's needs  
// The data to be imported defines which data to import.  
} 
} 
if ($sy) { $sy = rtrim($sy, '|'); } 
$arr = explode('|',$sy); 
$key = array_slice($arr,0,$num); // This array is csv The title of the document is the product id, The headline, the selling points and so on  
$skey = array(); 
$length = array(); 
$co = count($arr); 
$p = $co/$num; // Figure out the length of the data to take out  
for($j=0;$j<$p;$j++){ 
$offset=($j-1)*$num; // Offsets, like pagination 1 Like, I took it here according to the offset 1 An array is 1 Information about a commodity.  
if($j==0){ 
$length[] = array_slice($arr,0,$num); 
}else{ 
$length[] = array_slice($arr,$num+$offset,$num);// What fields and goods are there to pull out  
} 
} 
$arrtitle = array(); 
$arrfileds = array(); 
$arrtagname = DB::select(' Field identification ', ' The field names ')->from(' Field in the 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]].' The text '; 
} 
} else { 
if ($temarr[0] != 'pic') { // Is to take out the field is to take out the picture  
$arrtitle[] = $arrfileds[$temarr[0]]; 
} 
} 
} 

} 

$skey = array(); 
$order = array(); 
$order[] = 'act_tag'; 
$order[] = 'channel_tag'; 
$order[] = 'created_time'; 
$order[] = 'orderby'; 
$rows =''; 
$f = $co/$num;// So let's figure out how many items there are  
for($p=0;$p<count($arrtitle);$p++){ 
// Here is to find out the data you need according to your own needs, and find out the Corresponding English identity in the table by identifying the commodity field that the user needs.  
$skey[]= DB::select(' Field identification ')->from(' Field in the table ')->where(' The field names ', '=', $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); 
$count1 = count($skeys); // Number of fields  
if(!empty($length)){ 
for($x=1;$x<$f;$x++){ // Figure out how many times you're going through the cycle with how many items there are  
$orders = array(); 
$orders[] = $act_tag; 
$orders[] = $channel_tag; 
$orders[] = time(); 
$newlen = array_merge($orders,$length[$x]); 
if($count1 !== count($newlen)){ // If the length of the item field is different from the length of the item field, then the user has a field that is not entered  
$newrs = array(); 
echo "<script type=\"text/javascript\">alert(\"<font color=#f00;>".' Please check the number, '.($x-1).' Goods! '.' Import failed! '."</font>"); </script>"; 
fclose($handle); 
exit(); 
}else{ //start 
$arrimport = array_combine($skeys,$newlen); // If the two arrays are equal I merge the arrays and import them csv The date inside is changed to timestamp and stored in 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 number, '.($x-1).' Goods! '.' Import failed! '."</font>"); </script>"; 
fclose($handle); 
exit(); 
} 
if(count($skeys) == count($newrs)){ 
DB::insert(' Goods 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 goods you imported are empty! '."</font>"); </script>"; 
}else{ 
echo "<script type=\"text/javascript\">alert(\"<font color=#f00;>".' A successful import '."<font color=#f00;>".($row-1)."</font>".' Goods! '."</font>"); 
} 
fclose($handle); 
} 
?> 

Above is what I need to do for the csv import processing. It may be different from your import, but some of the code will always help you!
Here is a simple import:
 
<form enctype="multipart/form-data" action="import.php" method="POST"> 
 Import the template  
<label for=" File selection "> File selection: </label><input name="csv_goods" type="file" /> 
<input type="submit" value=" The import " 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 ' Incorrect file format , Please re-upload !'; 
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 re-upload !'; 
exit; 
} 

$row = 0; 
while ($data = fgetcsv($handle,1000,',')){ 
//echo "<font color=red>$row</font>"; // So we know how many rows there are  
$row++; 
if ($row == 1) 
continue; 
$num = count($data); 
//  This will output the data for each cell in each row in turn  
for ($i=0; $i<$num; $i++){ 
echo $data[$i]."<br>"; 
//  The data is processed here  
} 
} 

fclose($handle); 
} 

?> 

Related articles: