从codeigniter mysql下载csv [英] Download csv from codeigniter mysql

查看:102
本文介绍了从codeigniter mysql下载csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我缺少一些明显的东西。我尝试将数据集从MySQL查询导出到CSV而不打印到浏览器。

I think I'm missing something obvious. I'm trying to export a dataset from a MySQL query to CSV without printing it to the browser.

这是我的代码:

<?php

$this->load->helper('download');
$list = $stories;
$fp = fopen('php://output', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

$data = file_get_contents('php://output'); // Read the file's contents
$name = 'data.csv';
force_download($name, $data);
fclose($fp);

?>

$ stories MySQL查询。

目前,一切打印到浏览器没有错误,没有下载,但我想强制CSV下载。我该如何做?

Currently everything prints to the browser with no errors and no download but I would like to force a CSV download. How can I do this?

最终工作代码:

 $this->load->helper('download');

    $list = $stories;
    $fp = fopen('php://output', 'w');
    foreach ($list as $fields) {
        fputcsv($fp, $fields);
        }

    $data = file_get_contents('php://output'); 
    $name = 'data.csv';

    // Build the headers to push out the file properly.
    header('Pragma: public');     // required
    header('Expires: 0');         // no cache
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Cache-Control: private',false);
    header('Content-Disposition: attachment; filename="'.basename($name).'"');  // Add the file name
    header('Content-Transfer-Encoding: binary');
    header('Connection: close');
    exit();

    force_download($name, $data);
    fclose($fp);


推荐答案

Codeigniter force_download()函数集。如果确实要去屏幕,我会怀疑有必要的标题丢失。您可以添加以下标头到您的代码设置正确的csv下载头(缓存控制将确保每次新鲜的数据下载:

I can't tell what headers are set from the Codeigniter force_download() function sets. If it is indeed going to the screen I would suspect the necessary headers are missing. You can add the below headers to your code to set correct csv dowload headers (The cache control will ensure fresh data download each time:

header('Content-Description: File Transfer');
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename='.$name);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));

这篇关于从codeigniter mysql下载csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆