用php创buildcsv文件

我想创build一个csv文件,但是当我运行代码时,它会返回一个银行页面并且没有csv文件。 我使用PHP 5.我使用下面的代码:

<?php $data = array ('aaa,bbb,ccc,dddd', '123,456,789', '"aaa","bbb"'); $fp = fopen('data.csv', 'w'); foreach($data as $line){ $val = explode(",",$line); fputcsv($fp, $val); } fclose($fp); ?> 

谢谢!

它是空白的,因为你正在写入file 。 你应该使用php://output来写output ,并发送头信息来表示它的csv。

 header('Content-Type: application/excel'); header('Content-Disposition: attachment; filename="sample.csv"'); $data = array( 'aaa,bbb,ccc,dddd', '123,456,789', '"aaa","bbb"' ); $fp = fopen('php://output', 'w'); foreach ( $data as $line ) { $val = explode(",", $line); fputcsv($fp, $val); } fclose($fp); 

@爸爸的回答很好。 但为什么使用explode作为fputscv采取数组作为参数?

例如,如果你有三列,四行文件,这里是一个更直的版本:

 header('Content-Type: application/excel'); header('Content-Disposition: attachment; filename="sample.csv"'); $user_CSV[0] = array('first_name', 'last_name', 'age'); // very simple to increment with i++ if looping through a database result $user_CSV[1] = array('Quentin', 'Del Viento', 34); $user_CSV[2] = array('Antoine', 'Del Torro', 55); $user_CSV[3] = array('Arthur', 'Vincente', 15); $fp = fopen('php://output', 'w'); foreach ($user_CSV as $line) { // though CSV stands for "comma separated value" // in many countries (including France) separator is ";" fputcsv($fp, $line, ','); } fclose($fp); 

我希望这个例子对你有用

 $data= "Sr. No.,Vendor Name,Cargo Type,Amount,Delivery Address,Pickup Time,Delivery Time\n"; $i = 1; if(!empty($detail)) { foreach ($detail as $list) { $data .= $i.","; $data .= any data $data .= any data $data .= any data $data .= any data $data .= any data $data .= any data $data .="\n"; $i++; } } header("Content-Type: application/csv"); $csv_filename = 'anyfilename.xlsx'; header("Content-Disposition:attachment;filename=".$csv_filename); $fd = fopen ($csv_filename, "w"); fputs($fd,$data); fclose($fd); echo $data; die();