PHP fgetcsv Definitions and usage
The PHP fgetcsv () function reads a line from the file pointer and resolves the CSV field.
Like PHP fgets (), the difference is that PHP fgetcsv () parses the read rows and finds the CSV-formatted fields, and then returns an array containing the fields.
Fgetcsv () returns FALSE when an error occurs, including when the end of the file is encountered.
Note: from php 4.3.5, the operation of PHP fgetcsv () is binary safe.
Grammar
Fgetcsv (File,length,separator,enclosure) |
Parameters |
Describe |
File |
Necessary. Specify the files to be inspected. |
Length |
Optional. Specify the maximum length of the line. Must be greater than the longest row in the CVS file. This parameter is optional in PHP 5. is required prior to PHP 5. If the parameter is omitted (set to 0 in a later version of PHP 5.0.4), there is no limit to the length, but the execution efficiency may be affected. |
Separator |
Optional. Sets the field specifier (only one character is allowed), and the default value is a comma. |
Enclosure |
Optional. Sets the field wrap character (only one character is allowed), and the default value is double quotes. This parameter is added in the PHP 4.3.0. |
Tips and comments
Note: The empty row 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 sensitive to locale settings. For example, LANG is set to en_US. UTF-8, a single byte-encoded file can have a read error.
Note: You can activate the auto_detect_line_endings run-time configuration option if you encounter a line terminator that PHP does not recognize the Macintosh file while reading the file.
Example 1
Copy Code code 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 Code code 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] => M Artin [3] => USA)
windows and Linux compatibility issues
I have a problem today. The Linux platform under the fgetcsv processing of the empty data generated at first thought that the PHP version of the problem, in fact, and the version is not related to the development of the Windows colleagues are no problem, and their own books and servers, and the use of Linux system colleagues have empty data problems
Google a bit
Set region: Simplified Chinese, UTF-8 encoding
Copy Code code as follows:
SetLocale (Lc_all, ' ZH_CN. UTF-8 ');