您可以使用內置的fputcsv()你的陣列來生成與陣列正確的CSV行,所以你會在有循環和收集線。像:
$f = fopen("tmp.csv", "w");
foreach ($array as $line) {
fputcsv($f, $line)
}
爲了使瀏覽器提供的「另存爲」對話框中,您需要發送HTTP標頭是這樣的(見更多有關rfc這個頭):
header('Content-Disposition: attachment; filename="filename.csv";');
將所有內容一起:
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
// open raw memory as file so no temp files needed, you might run out of memory though
$f = fopen('php://memory', 'w');
// loop over the input array
foreach ($array as $line) {
// generate csv lines from the inner arrays
fputcsv($f, $line, $delimiter);
}
// reset the file pointer to the start of the file
fseek($f, 0);
// tell the browser it's going to be a csv file
header('Content-Type: application/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachment; filename="'.$filename.'";');
// make php send the generated csv lines to the browser
fpassthru($f);
}
而且你可以使用它像這樣:
array_to_csv_download(array(
array(1,2,3,4), // this array is going to be the first row
array(1,2,3,4)), // this array is going to be the second row
"numbers.csv"
);
更新:
取而代之的php://memory
您還可以使用php://output
的文件描述符,並尋求與這樣做掉:
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="'.$filename.'";');
// open the "output" stream
// see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq
$f = fopen('php://output', 'w');
foreach ($array as $line) {
fputcsv($f, $line, $delimiter);
}
}
phpExcel一個CSV文件是有點太much..http://php.net/manual/en/function。 fputcsv.php – 2013-04-27 11:39:33
顯示您的數組結構,並提供一些代碼將元素轉換爲csv – 2013-04-27 11:43:54
@半快我已經在帖子中添加了數組結構 – user2302780 2013-04-27 12:09:56