php中下载csv文件,如何从php脚本创建和下载csv文件?

933c32894498a25dcd2308946ce40e5a.png

富国沪深

您可以为数组使用内置的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);    }}   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值