php将array变成csv格式

本文介绍了一种使用PHP将数组转换为CSV文件并提供下载的方法。通过直接在内存中生成CSV内容,避免了临时文件的使用,提高了效率。此外,还展示了如何设置HTTP头来确保文件正确下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
 2     // open raw memory as file so no temp files needed, you might run out of memory though
 3     $f = fopen('php://memory', 'w'); 
 4     // loop over the input array
 5     foreach ($array as $line) { 
 6         // generate csv lines from the inner arrays
 7         fputcsv($f, $line, $delimiter); 
 8     }
 9     // rewrind the "file" with the csv lines
10     fseek($f, 0);
11     // tell the browser it's going to be a csv file
12     header('Content-Type: application/csv');
13     // tell the browser we want to save it instead of displaying it
14     header('Content-Disposition: attachement; filename="'.$filename.'";');
15     // make php send the generated csv lines to the browser
16     fpassthru($f);
17 }

 

 1         $f = fopen('php://memory', 'w'); 
 2 //        $lca=implode("\r\n",$new_rcarray);
 3 //        fwrite($f,$lca);
 4 //        fseek($f, 0);
 5         foreach ($new_rcarray as $v){
 6             fwrite($f,$v."\r\n");
 7         }
 8         fseek($f, 0);
 9         
10         header("Content-type:text/csv");
11         header("Content-Type: application/force-download");
12         header("Content-Disposition: attachment; filename=local_calling_area.txt");
13         header('Expires:0');
14         header('Pragma:public');
15         //echo "\xFF\xFE".mb_convert_encoding($lca,'UCS-2LE','UTF-8');
16         fpassthru($f);

 

转载于:https://www.cnblogs.com/sexy/articles/3875624.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值