php tutorial fgetcsv read csv file code
function get_csv_contents ($ file_target) {
$ handle = fopen ($ file_target, 'r');
while ($ data = fgetcsv ($ handle, 1000, ",")) {
$ num = count ($ data);
echo "<p> $ num fields in line $ row: <br> n";
$ row ++;
for ($ c = 0; $ c <$ num; $ c ++) {
echo $ data [$ c]. "<br> n" ;;
/ * echo getUTFString ($ data [$ c]) * /
}
}
fclose ($ handle);
}
array fgetcsv (int handle [, int length [, string delimiter [, string enclosure]]])
handle
A valid file pointer generated by fopen (), popen (), or fsockopen ().
length (optional)
Must be greater than the longest line in the CVS file. In PHP 5 this parameter is optional. If you omit (set to 0 in PHP 5.0.4 and later) this parameter, then there is no limit on the length, but this can affect the efficiency of your execution.
delimiter (optional)
Set the field delimiter (only one character allowed), the default is comma.
enclosure (optional)
Set the field surround (only one character allowed), the default is double quotation marks. This parameter is added in PHP 4.3.0.
Similar to fgets (), except that fgetcsv () parses the read line and finds the fields in CSV format and returns an array of those fields.
Fgetcsv () returns FALSE error, including the end of the file encountered.
Note: Blank lines in a CSV file will be returned as an array containing a single null field and will not be treated as an error.
Example 1. Read and display the entire contents of the CSV file
<? php
$ row = 1;
$ handle = fopen ("test.csv", "r");
while ($ data = fgetcsv ($ handle, 1000, ",")) {
$ num = count ($ data);
echo "<p> $ num fields in line $ row: <br> n";
$ row ++;
for ($ c = 0; $ c <$ num; $ c ++) {
echo $ data [$ c]. "<br> n";
}
}
fclose ($ handle);