如何创build和从PHP脚本下载CSV文件?

我是一个新手程序员,我search了很多关于我的问题,但找不到有用的解决scheme或教程。

我的目标是我有一个PHP数组,数组元素显示在页面上的列表中。

我想添加一个选项,这样,如果用户想要,他/她可以创build一个包含数组元素的CSV文件并下载它。

我不知道该怎么做 我也search了很多。 但还没有find有用的资源。

请给我提供一些教程或解决scheme或build议,由我自己来实施。 由于我是新手,请提供易于实施的解决scheme。

我的数组看起来像:

Array ( [0] => Array ( [fs_id] => 4c524d8abfc6ef3b201f489c [name] => restaurant [lat] => 40.702692 [lng] => -74.012869 [address] => new york [postalCode] => [city] => NEW YORK [state] => ny [business_type] => BBQ Joint [url] => ) ) 

您可以使用内置的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文件描述符,并取消search,例如:

 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); } } 

我没有足够的信誉来回复@ complex857解决scheme。 它工作的很好,但我不得不补充; 在Content-Disposition头部的末尾。 没有它,浏览器在文件名末尾添加两个破折号(例如,代替“export.csv”,文件保存为“export.csv–”)。 可能它会试图在标题行结束处理\ r \ n。

正确的行应该是这样的:

 header('Content-Disposition: attachment;filename="'.$filename.'";'); 

如果CSV中包含UTF-8字符,则必须通过更改Content-Type行将编码更改为UTF-8:

 header('Content-Type: application/csv; charset=UTF-8'); 

另外,我发现使用rewind()而不是fseek()更优雅:

 rewind($f); 

感谢您的解决scheme!

 Try... csv download. <?php mysql_connect('hostname', 'username', 'password'); mysql_select_db('dbname'); $qry = mysql_query("SELECT * FROM tablename"); $data = ""; while($row = mysql_fetch_array($qry)) { $data .= $row['field1'].",".$row['field2'].",".$row['field3'].",".$row['field4']."\n"; } header('Content-Type: application/csv'); header('Content-Disposition: attachement; filename="filename.csv"'); echo $data; exit(); ?> 

使用下面的代码将一个php数组转换为CSV

 $ROW=db_export_data();//Will return a php array header("Content-type: application/csv"); header("Content-Disposition: attachment; filename=test.csv"); $fp = fopen('php://output', 'w'); $i=0; foreach ($ROW as $row) { fputcsv($fp, $row); $i++; } fclose($fp); 

如果你的数组结构总是以这种精确的方式是多维的,那么我们可以遍历这样的元素:

 $fh = fopen('somefile.csv', 'w') or die('Cannot open the file'); for( $i=0; $i<count($arr); $i++ ){ $str = implode( ',', $arr[$i] ); fwrite( $fh, $str ); fwrite( $fh, "\n" ); } fclose($fh); 

这是做这件事的一种方法…你可以手动做,但这种方式更快,更容易理解和阅读。

然后,你会pipe理你的标题是什么complex857正在做的吐出文件。 如果你不再需要它,你可以使用unlink()来删除文件,或者如果你愿意的话,你可以把它放在服务器上。