php 从codeigniter mysql下载csv

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20840274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:36:04  来源:igfitidea点击:

Download csv from codeigniter mysql

phpmysqlcodeignitercsv

提问by EnduroDave

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.

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

Here's my code:

这是我的代码:

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

?>

$storiesis my array created from the MySQL query.

$stories是我从 MySQL 查询创建的数组。

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?

目前一切都打印到浏览器,没有错误,也没有下载,但我想强制下载 CSV。我怎样才能做到这一点?



final working code:

最终工作代码:

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

回答by Hareesh

You can call model CSV()from your controller as

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

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

and in the model

并在模型中

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

Your File will start downloading

您的文件将开始下载

回答by shaunl

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:

我不知道从 Codeigniterforce_download()函数集中设置了哪些标头。如果它确实进入屏幕,我会怀疑缺少必要的标题。您可以将以下标题添加到您的代码中以设置正确的 csv 下载标题(缓存控件将确保每次下载新数据:

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

回答by stren

i am use this and its work

我正在使用这个和它的工作

  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;

回答by Nikhil Borad

If you are trying to generate reports in csv format then it will quite easy with codeigniter.

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

Place this code in your Controller

将此代码放在您的控制器中

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


Put this code into Model

将此代码放入模型中

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


report_success.phpis just Successful Notification.

report_success.php只是成功通知。

Your Report is being Exported. Thank you

正在导出您的报告。谢谢



Finally Your "file.csv" is generated. its basically stored at physical storage. In CodeIgniter/application/third-party/file.csv

最后生成您的“file.csv”。它基本上存储在物理存储中。在CodeIgniter/application/third-party/file.csv



it works. it will help you.

有用。它会帮助你。

回答by Ashish pathak

Here we have sample result set from MySQL and want to export in CSV file.

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

Step 1: Get MySql data in key value pair.

第一步:在键值对中获取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')
        );

Step 2: PHP code to get options type and force to browser download file instead of display.

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

Step 3: Define html layout for display data in table and button to fire export-to-csv action.

第 3 步:定义用于在表格和按钮中显示数据的 html 布局以触发导出到 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>

Step 3: Now we will use jQuery code to get click event.

第 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>