The method of generating CSV file in PHP is very simple, here I introduce myself to use an example, the array directly to the CSV file output, there is a need to know the friend can refer to.
Cases
The code is as follows |
Copy Code |
$data = Array ( Array (' Row_1_col_1 ', ' row_1_col_2 ', ' row_1_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 = + $val 2) { $val [$key] = iconv (' utf-8 ', ' GBK ', $val 2);//CSV Excel support GBK encoding, be sure to convert, otherwise garbled } Fputcsv ($outputBuffer, $val); } Fclose ($outputBuffer); }
?> |
Example 2
See an instance of reading a CSV file
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 |
/** by www.bKjia.c0m */ $row = 1; $handle = fopen ("File.csv", "R"); Fgetcsv () parses the read-in row and finds the CSV-formatted field and returns an array containing the fields. while ($data = Fgetcsv ($handle, 1000, ",")) { $num = count ($data); echo " $num Fields $row: n "; $row + +; for ($c =0; $c < $num; $c + +) { Note the problem of Chinese garbled $data [$c]=iconv ("GBK", "Utf-8//ignore", $data [$c]); echo $data [$c]. " n "; } } Fclose ($handle); ?> |
http://www.bkjia.com/PHPjc/632920.html www.bkjia.com true http://www.bkjia.com/PHPjc/632920.html techarticle The method of generating CSV file in PHP is very simple, here I introduce myself to use an example, the array directly to the CSV file output, there is a need to know the friend can refer to. Example ...