PHP fgetcsv definition and usage of with windows and linux compatibility issues

  • 2020-05-16 06:37:27
  • OfStack

Definition and usage of PHP fgetcsv

The PHP fgetcsv() function reads in a line from the file pointer and parses the CSV field.
Similar to PHP fgets(), PHP fgetcsv() parses the rows read in and finds the fields in CSV format, then returns an array of these fields.

fgetcsv() returns FALSE when an error occurs, including when the end of the file is encountered.

Note: from PHP 4.3.5, PHP fgetcsv() is safe in base 2.

grammar

fgetcsv(file,length,separator,enclosure) parameter describe file A necessity. Documents to be examined. length Optional. Specifies the maximum length of the line. Must be larger than the longest line in the CVS file.
This parameter is optional in PHP 5. It is required before PHP 5.
If you ignore the parameter (set to 0 in PHP 5.0.4 and later), there is no limit to the length, but it may affect performance. separator Optional. Set the field delimiter (only 1 character allowed) to a comma by default. enclosure Optional. Set the field surround character (only 1 character allowed) to double quotation marks by default.
This parameter was added in PHP 4.3.0. Hints and comments

Note: the empty line 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 locale-sensitive. For example, if LANG is set to en_US.UTF-8, single-byte encoded files will be read incorrectly.
Note: the auto_detect_line_endings runtime configuration option can be activated if PHP does not recognize the end of the line in the Macintosh file when reading the file.

Example 1
 
<?php 
$file = fopen("contacts.csv","r"); 
print_r(fgetcsv($file)); 
fclose($file); 
?> 


CSV file:
George, John, Thomas, USA James, Adrew, Martin, USA
The output is similar to:
Array ([0] = > George [1] = > John [2] = > Thomas [3] = > USA )

Example 2
 
   <?php 
$file = fopen("contacts.csv","r"); 
while(! feof($file)) { print_r(fgetcsv($file)); 
} fclose($file); 
?> 

CSV file:
George, John, Thomas, USA James, Adrew, Martin, USA
The output is similar to:
Array ([0] = > George [1] = > John [2] = > Thomas [3] = > USA Array ( [0] = > James [1] = > Adrew [2] = > Martin [3] = > USA )

Compatibility issues with windows and linux

There is a problem reported today that the idle data processed by fgetcsv on linux platform was initially thought to be a problem with php version, but in fact it has nothing to do with the version. None of the colleagues who developed under window had any problem, while the colleagues who used linux system and their own laptops and servers had any problem with empty data

Under the google1

Setting area: simplified Chinese, UTF-8 code
 
setlocale(LC_ALL, 'zh_CN.UTF-8'); 

Related articles: