使用 PHP Codeigniter 框架生成 CSV 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19675132/
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 19:51:00  来源:igfitidea点击:

Generate CSV file using PHP Codeigniter Framework

phpcodeigniter

提问by Serma

I want to generate a csv file, using data from a database. How does one do this in PHP CodeIgniter framework?

我想使用数据库中的数据生成一个 csv 文件。在 PHP CodeIgniter 框架中如何做到这一点?

回答by Praveen D

use csv_helper to generate csv file.

使用 csv_helper 生成 csv 文件。

Follow this below link to get solution,

按照以下链接获取解决方案,

http://www.code2learn.com/2012/03/generating-csv-file-using-codeigniter.html

http://www.code2learn.com/2012/03/generating-csv-file-using-codeigniter.html

回答by Asif

function query_to_csv( $query, $filename, $attachment = false, $headers = true) {

    if($attachment) {
        // send response headers to the browser
        header( 'Content-Type: text/csv' );
        header( 'Content-Disposition: attachment;filename='.$filename);
        $fp = fopen('php://output', 'w');
    } else {
        $fp = fopen($filename, 'w');
    }

    $result = mysql_query($query);

    if($headers) {
        // output header row (if at least one row exists)
        $row = mysql_fetch_assoc($result);
        if($row) {
            fputcsv($fp, array_keys($row));
            // reset pointer back to beginning
            mysql_data_seek($result, 0);
        }
    }

    while($row = mysql_fetch_assoc($result)) {
        fputcsv($fp, $row);
    }

    fclose($fp);
    exit;
}

回答by Muhammad Raheel

Take a look at this answer of mine and you will know exactly how you can do it.

看看我的这个答案,你就会知道如何做到这一点。

Reports in Codeigniter

Codeigniter 中的报告

You need to use Codeigniter Database Utility Class

您需要使用Codeigniter 数据库实用程序类

And need to return query instead of result_arrayor result

并且需要返回查询而不是result_arrayresult