从codeigniter mysql下载csv

时间:2013-12-30 13:10:42

标签: php mysql codeigniter csv

我想我错过了一些明显的东西。我试图将数据集从MySQL查询导出到CSV而不将其打印到浏览器。

这是我的代码:

<?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下载。我怎么能这样做?


最终工作代码:

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

5 个答案:

答案 0 :(得分:13)

您可以从控制器中调用模型CSV()

$this->load->model('Users_model');
$this->Users_model->csv();

并在模型中

function csv()
{
        $this->load->dbutil();
        $this->load->helper('file');
        $this->load->helper('download');
        $query = $this->db->query("SELECT * FROM Users");
        $delimiter = ",";
        $newline = "\r\n";
        $data = $this->dbutil->csv_from_result($query, $delimiter, $newline);
        force_download('CSV_Report.csv', $data);
}

您的文件将开始下载

答案 1 :(得分:3)

我无法分辨Codeigniter force_download()函数集中设置的标题。如果确实要进入屏幕,我会怀疑缺少必要的标题。您可以在代码中添加以下标题以设置正确的csv dowload标头(缓存控件将确保每次都下载新数据:

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

答案 2 :(得分:1)

如果您尝试使用csv格式生成报告,那么使用codeigniter会很容易。

将此代码放入您的控制器

function get_report()
{
    $this->load->model('Main_Model');
    $this->load->dbutil();
    $this->load->helper('file');
    /* get the object   */
    $report = $this->Main_Model->print_report();
    $delimiter = ",";
    $newline = "\r\n";
    $new_report = $this->dbutil->csv_from_result($report, $delimiter, $newline);
    write_file( 'application/third_party/file.csv', $new_report);
    $this->load->view('report_success.php');
}

将此代码放入模型

public function print_report()
{
    return $query = $this->db->query("SELECT * FROM Table_name");
} 

report_success.php只是成功通知。

您的报告正在导出。谢谢


最后你的&#34; file.csv&#34;生成。 它基本上存储在物理存储器中。 在CodeIgniter/application/third-party/file.csv


它有效。 它会帮助你。

答案 3 :(得分:1)

我正在使用这个及其作品

  header('Content-Type: text/csv; charset=utf-8');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header("Content-Disposition: attachment; filename=backup" . date('y-m-d') . ".csv");
            header('Last-Modified: ' . date('D M j G:i:s T Y'));
            $outss = fopen("php://output", "w");
            $this->db->order_by('ID', 'DESC');
            $query = $this->db->get('urls');
            foreach ($query->result_array() as $rows) {
                fputcsv($outss, $rows);
            }
            fclose($outss);
            return;

答案 4 :(得分:0)

这里我们有来自MySQL的示例结果集,并希望以CSV文件导出。

第1步:在密钥值对中获取MySql数据。

$data = array(
         '0' => array('Name'=> 'Parvez', 'Status' =>'complete', 'Priority'=>'Low', 'Salary'=>'001'),
         '1' => array('Name'=> 'Alam', 'Status' =>'inprogress', 'Priority'=>'Low', 'Salary'=>'111'),
         '2' => array('Name'=> 'Sunnay', 'Status' =>'hold', 'Priority'=>'Low', 'Salary'=>'333'),
         '3' => array('Name'=> 'Amir', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'444'),
         '4' => array('Name'=> 'Amir1', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'777'),
         '5' => array('Name'=> 'Amir2', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'777')
        );

第2步:PHP代码获取选项类型并强制浏览器下载文件而非显示。

if(isset($_POST["ExportType"]))

{

switch($_POST["ExportType"])
{
    case "export-to-csv" :
        // Submission from
        $filename = $_POST["ExportType"] . ".csv";       
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename=\"$filename\"");
        ExportCSVFile($data);
        //$_POST["ExportType"] = '';
        exit();
    default :
        die("Unknown action : ".$_POST["action"]);
        break;
}

}

function ExportCSVFile($records) {
    // create a file pointer connected to the output stream
    $fh = fopen( 'php://output', 'w' );
    $heading = false;
        if(!empty($records))
          foreach($records as $row) {
            if(!$heading) {
              // output the column headings
              fputcsv($fh, array_keys($row));
              $heading = true;
            }
            // loop over the rows, outputting them
             fputcsv($fh, array_values($row));

          }
          fclose($fh);
}

第3步:为表格和按钮定义显示数据的html布局,以触发export-to-csv操作。

<div><a href="javascript:void(0)" id="export-to-csv">Export to csv</a></div>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" id="export-form">
                    <input type="hidden" value='' id='hidden-type' name='ExportType'/>
                  </form>
              <table id="" class="table table-striped table-bordered">
                <tr>
                    <th>Name</th>
                    <th>Status</th>
                    <th>Priority</th>
                    <th>Salary</th>
              </tr>
            <tbody>
              <?php foreach($data as $row):?>
              <tr>
              <td><?php echo $row ['Name']?></td>
              <td><?php echo $row ['Status']?></td>
              <td><?php echo $row ['Priority']?></td>
              <td><?php echo $row ['Salary']?></td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>

第3步:现在我们将使用jQuery代码获取点击事件。

 <script  type="text/javascript">
$(document).ready(function() {
jQuery('#export-to-csv').bind("click", function() {
var target = $(this).attr('id');
switch(target) {
    case 'export-to-csv' :
    $('#hidden-type').val(target);
    //alert($('#hidden-type').val());
    $('#export-form').submit();
    $('#hidden-type').val('');
    break
}
});
    });
</script>