PHP fgetcsv definition and usage
The PHP fgetcsv () function reads a row from the file pointer and parses the CSV field.
Similar to PHP fgets (), the difference is that PHP fgetcsv () parses the rows read, finds fields in CSV format, and returns an array containing these fields.
If an error occurs in fgetcsv (), FALSE is returned, including when the file ends.
Note: from PHP 4.3.5, PHP fgetcsv () operations are binary safe.
Syntax
Fgetcsv (file, length, separator, enclosure) |
Parameters |
Description |
File |
Required. Specifies the file to be checked. |
Length |
Optional. Specifies the maximum length of a row. It must be greater than the maximum row in the CVS file. This parameter is optional in PHP 5. Required Before PHP 5. If this parameter is ignored (set to 0 in PHP 5.0.4 and later versions), the length is not limited, but the execution efficiency may be affected. |
Separator |
Optional. Set the field delimiter (only one character is allowed). The default value is comma. |
Enclosure |
Optional. Set the field surround character (only one character is allowed). The default value is double quotation marks. This parameter is added in PHP 4.3.0. |
Tips and comments
Note: Empty rows 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 region settings. For example, if LANG is set to a en_US.UTF-8, a single-byte encoded file will have a read error.
Note: If PHP cannot recognize the row terminator of the Macintosh file when reading the file, you can activate the auto_detect_line_endings runtime configuration option.
Example 1
Copy codeThe Code is as follows:
<? 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:
Array ([0] => George [1] => John [2] => Thomas [3] => USA)
Example 2
Copy codeThe Code is as follows:
<? 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:
Array ([0] => George [1] => John [2] => Thomas [3] => USA Array ([0] => James [1] => Adrew [2] => Martin [3] => USA)
Compatibility issues in windows and linux
I reported a problem today that the free data processed by fgetcsv on the linux platform was generated and thought it was a php version problem at first. In fact, it is not related to the version, and the Development colleagues in the window are not correct, however, my colleagues in the local and server, and linux system, all experienced the problem of empty data.
Google
Set area: Simplified Chinese, UTF-8 Encoding
Copy codeThe Code is as follows:
Setlocale (LC_ALL, 'zh _ CN.UTF-8 ');