Linux fgetcsv gets the array element as an empty string

  • 2020-05-10 17:49:32
  • OfStack

But on servers, many use Linux servers and source programs use UTF-8, which can easily cause character encoding problems.

If you just transcode the CSV file to UTF-8, there will be no problem on the Windows server,

On RedHat5.5, if the contents of a column in fgetcsv are in Chinese, the array elements corresponding to that column are empty strings, while English is normal.

At this point, you need to set the area:

setlocale(LC_ALL, 'zh_CN.UTF-8');
The following code
 
//  The uploaded CSV file , Usually use Excel The editor's GBK coding , 
//  And the source code is UTF-8, Transcoding is required  
file_put_contents($new_file, iconv('GBK', 'UTF-8', file_get_contents($new_file))); 

//ini_set('auto_detect_line_endings', true); 
//  The Settings area : Simplified Chinese ,UTF-8 coding  
setlocale(LC_ALL, 'zh_CN.UTF-8'); 
//  Open the CSV file  
$handle = fopen($new_file, 'r'); 
//  Remove the column header  
$data_heads = fgetcsv($handle); 

Related articles: