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.
Example
The Code is as follows: |
Copy code |
<? Php $ 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: |
Copy code |
<? Php /** 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 "<p> $ num fields in line $ row: <br> 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]. "<br> n "; } } Fclose ($ handle ); ?> |