Generate a csv file using the phparray array. The method for generating csv files in php is very simple. here I will introduce an instance that I used to convert the array directly into a csv file for output. For more information, see. For example, it is very simple to generate a csv file in php. here I will introduce an instance used to directly convert the array into a csv file and output it. For more information, see.
Example
| The code is as follows: |
|
|
$ Data = array (
Array ('row _ partition col_1 ', 'row _ partition col_2', 'row _ partition col_3 '),
Array ('row _ 2_col_1 ', 'row _ 2_col_2', 'row _ 2_col_3 '),
Array ('row _ 3_col_1 ', 'row _ 3_col_2', 'row _ 3_col_3 '),
);
$ Filename = "example ";
Header ("Content-type: text/csv ");
Header ("Content-Disposition: attachment; filename=#filename=.csv ");
Header ("Pragma: no-cache ");
Header ("Expires: 0 ");
OutputCSV ($ data );
Function outputCSV ($ data ){
$ OutputBuffer = fopen ("php: // output", 'w ');
Foreach ($ data as $ val ){
Foreach ($ val as $ key => $ val2 ){
$ Val [$ key] = iconv ('utf-8', 'gbk', $ val2); // CSV Excel supports gbk encoding and must be converted; otherwise garbled
}
Fputcsv ($ outputBuffer, $ val );
}
Fclose ($ outputBuffer );
}
?> |
Example 2
View an instance for reading csv files
Read cvs, use the fgetcsv () file pointer to read a row and parse the CSV field
For example, I want to read the following csv file
| The code is as follows: |
|
|
/** By www. bKjia. c0m */
$ Row = 1;
$ Handle = fopen ("file.csv", "r ");
// Fgetcsv () parses the read rows, finds fields in CSV format, and returns an array containing these fields.
While ($ data = fgetcsv ($ handle, 1000 ,",")){
$ Num = count ($ data );
Echo"
$ Num fields in line $ row:
N ";
$ Row ++;
For ($ c = 0; $ c <$ num; $ c ++ ){
// Pay attention to Chinese garbled characters
$ Data [$ c] = iconv ("gbk", "UTF-8 // IGNORE", $ data [$ c]);
Echo $ data [$ c]."
N ";
}
}
Fclose ($ handle );
?> |
Bytes. Example...