search
HomeBackend DevelopmentPHP TutorialHow to solve the problem of garbled characters when importing csv files into PHP_PHP Tutorial

Today I mainly want to write a method for importing csv files in php. In fact, there are a lot of them online. All can be implemented how to import. But I encountered two problems when importing. One was that the test had garbled characters when writing code on Windows, and then it was solved. The second one is that when it was submitted to the Linux system, garbled characters occurred again. I didn’t know the reason for the garbled code at first. At first I thought it was an error in the code svn submission. In the end, I asked a question in one of my groups. A friend of mine works in phpcms. He said that he encountered an error from Windows. When submitting to Linux, errors always occurred at first. Later, the cause was found to be garbled characters. Let’s get right to the point and see how to solve these two problems!

The problem is solved:

PHP reads the csv file, and the Chinese cannot be read on Windows. I immediately thought of a function mb_convert_encoding(); make the following settings $str = mb_convert_encoding ($str, "UTF-8", "GBK"); Then that's it. Of course, you can also use iconv(); to set iconv('GBK', "UTF-8//TRANSLIT//IGNORE", $str); as follows; these two functions can solve the problem of garbled characters on Windows.

Solution to problem two:

PHP reads the csv file, but Chinese cannot be read on Linux. I found the solution after Baidu and Google.

Just added it One line of code setlocale(LC_ALL, 'zh_CN'); Yes, it will blind your eyes. It's that simple, and if you didn't know, you could spend a lot of time figuring it out.
PHP setlocale() function explanation
Definition and usage

setlocale() function sets regional information (regional information).

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

Copy code The 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′);
Simplified: setlocale(LC_ALL, 'zh_CN');

The reason why I tell you about the setlocale() function is because when I imported the csv file into the Linux system, garbled characters occurred, including the use of mb_convert_encoding() and iconv( ) Both functions failed to solve the final problem. Finally, I added this sentence setlocale(LC_ALL, 'zh_CN'); in front of the code at the beginning of importing the csv file and it was easily done. Then I searched for information and found that the fgetcsv() function is sensitive to locale settings. For example, if LANG is set to en_US.UTF-8, single-byte encoded files will have read errors, so we need to set the culture. Specially shared with everyone.

I also tried the following code but couldn’t get it to work. These are the header settings for generating csv files. It might not work for me, but it might work for you. So I sorted it out and tried my best to help colleagues who encountered garbled characters when importing csv files, because it was really difficult to deal with it when there was no other way. Everyone can try it! There is always one that belongs to you.

Copy code The 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;
?>

Let’s take a closer look at the code for PHP to import csv files:

A brief introduction to the two functions,

The character encoding detected by mb_detect_encoding(), or the specified string cannot be detected Returns FALSE when encoding.

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

Note: As of PHP 4.3.5, the operation of fgetcsv() is binary safe.

Note: Empty lines in the CSV file will be 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. For example, if LANG is set to en_US.UTF-8, single-byte encoded files will have read errors.

Note: If you encounter that PHP cannot recognize the line ending characters of Macintosh files when reading the file, you can activate the auto_detect_line_endings runtime configuration option.
Copy code The code is as follows:

setlocale(LC_ALL, 'zh_CN'); //Set regional information (regional 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$str = (string)$data[$i].'|';
$str = mb_convert_encoding($str, "UTF-8", "GBK"); //The source code is known to be GBK and converted to utf-8
$sy .= $str; //What I do here is more complicated , use '|' to put all the contents in the csv file together with '|', because I am importing product information, and I need to define which 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 title in the csv file, which is the data of product id, title, selling point, etc.
$skey = array();
$length = array();
$co = count($arr);
$p = $co/$num; //Find the length of the data to be taken out
for($j=0;$ j$offset=($j-1)*$num; //Offset, just like paging, the array I take out based on the offset is a product information.
if($j==0){
$length[] = array_slice($arr,0,$num);
}else{
$length[] = array_slice($arr, $num+$offset,$num);//Get out which fields and products are there
}
}
$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') { //If the field is a picture, remove it
$arrtitle[] = $arrfileds[$temarr[0]];
}
}
}

}

$skey = array();
$order = array();
$order[] = 'act_tag' ;
$order[] = 'channel_tag';
$order[] = 'created_time';
$order[] = 'orderby';
$rows ='';
$ f = $co/$num;//Find out how many items there are
for($p=0;$p//This is based on your own needs Find the data you need, and use the product field identification required by the user to find the corresponding English identification in the table.
$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);
$count1 = count($skeys); //Number of fields
if(!empty($length)){
for($x=1; $x$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 product field is different from the length of the product, it means that the user has not entered any field
$newrs = array();
echo "";
fclose($handle);
exit();
}else{ //start
$arrimport = array_combine($skeys,$newlen); // If the two arrays are equal, I merge the arrays and change the date imported into the csv to a timestamp and store it in the database
if(!empty($arrimport['start_time'])){ $sta = strtotime($ armimport['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($ arrival['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('product table', array_values($skeys))
->values(array_values($newrs))
->execute();
}
} //end
}
}
if($row-1==(int)0){
echo "";
}else{
echo "

The above is the csv import process that I need to do for my work. It may be different from your import method, but some codes will always be helpful to you!
The following is a simple import:
Copy the code The code is as follows:


Import template



if (isset($_POST['import'])){

$file = $_FILES['csv_goods'];

$file_type = substr(strstr($file['name '],'.'),1);

// Check file format
if ($file_type != 'csv'){
echo 'The file format is incorrect, 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 "$row"; //You can know How many rows are there in total?
$row++;
if ($row == 1)
continue;
$num = count($data);
// Here will be output in each row in turn Data for each cell
for ($i=0; $iecho $data[$i]."
";
// in The data is processed here
}
}

fclose($handle);
}

?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/732387.htmlTechArticleToday I mainly want to write a method of importing csv files in php. In fact, there are a lot of them online. All can be implemented how to import. But I encountered two problems when importing. One is...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use