Cases
| The code is as follows |
Copy Code |
|
<?php
$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
Look at an instance that reads a CSV file
Read CVS, read a line using the Fgetcsv () file pointer, and parse the CSV field
For example, I want to read the following CSV file
| code is as follows |
copy code |
|
<?php
/** by www.111cn.net */
$row = 1;
$handle = fopen (" File.csv " , "R"); The
//fgetcsv () resolves the read rows and finds the fields in CSV format and returns an array containing those 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 + +) {
//Note the Chinese garbled problem
$data [$c]=iconv ("GBK "," Utf-8//ignore ", $data [$c]);
echo $data [$c]." <br>n ";
}
}
Fclose ($handle);
? |