简体   繁体   English

如何在Codeigniter中导出数组到CSV?

[英]How to export array to CSV in Codeigniter?

 $Data[] = array('x'=> $x, 'y'=> $y, 'z'=> $z, 'a'=> $a);

I want to export this array to CSV. I am using CodeIgniter.我想将这个数组导出到 CSV。我正在使用 CodeIgniter。

You can try this code for your export array to CSV.您可以尝试使用此代码将导出数组导出为 CSV。

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Import extends CI_Controller {

        public function __construct() {
            parent::__construct();
        }
        public function exports_data(){
            $data[] = array('x'=> $x, 'y'=> $y, 'z'=> $z, 'a'=> $a);
             header("Content-type: application/csv");
            header("Content-Disposition: attachment; filename=\"test".".csv\"");
            header("Pragma: no-cache");
            header("Expires: 0");

            $handle = fopen('php://output', 'w');

            foreach ($data as $data_array) {
                fputcsv($handle, $data_array);
            }
                fclose($handle);
            exit;
        }
}

I hope it will help you.我希望它会帮助你。

function exportEtpCsv(){
        $data[] = array('f_name'=> "Nishit", 'l_name'=> "patel", 'mobile'=> "999999999", 'gender'=> "male");
        header("Content-type: application/csv");
        header("Content-Disposition: attachment; filename=\"test".".csv\"");
        header("Pragma: no-cache");
        header("Expires: 0");

        $handle = fopen('php://output', 'w');
        fputcsv($handle, array("No","First Name","Last Name"));
        $cnt=1;
        foreach ($data as $key) {
            $narray=array($cnt,$key["f_name"],$key["l_name"]);
            fputcsv($handle, $narray);
        }
            fclose($handle);
        exit;
    }

This Solution is working for me you have to call exportCSV Function with CodeIgniter controller此解决方案对我有用,您必须使用 CodeIgniter 控制器调用 exportCSV 函数

 public function exportCSV(){ // file name $filename = 'users_'.date('Ymd').'.csv'; header("Content-Description: File Transfer"); header("Content-Disposition: attachment; filename=$filename"); header("Content-Type: application/csv; "); // get data from mysql // public function ViewDataa($table, $sel) { // $this->db->select($sel); // $this->db->from($table); // return $this->db->get()->result_array(); // } $usersData = $this->am->ViewDataa("eml_collection", "name, email, phone, Areyouarealtor"); // CSV header $header = array("Name","Email","Phone","Areyouarealtor"); $usersData //Will your Data array // file creation $file = fopen('php://output', 'w'); fputcsv($file, $header); foreach ($usersData as $key=>$line){ fputcsv($file,$line); } fclose($file); exit; }

Best Use is use csv_from_result()最佳用途是使用csv_from_result()

It Permits you to generate a CSV file from a query result.它允许您从查询结果生成 CSV 文件。 The first parameter of the method must contain the result object from your query.该方法的第一个参数必须包含查询的结果对象。

$this->load->dbutil();

$query = $this->db->query("SELECT * FROM mytable");

echo $this->dbutil->csv_from_result($query);

reference : https://www.codeigniter.com/user_guide/database/utilities.html#export-a-query-result-as-a-csv-file参考: https : //www.codeigniter.com/user_guide/database/utilities.html#export-a-query-result-as-a-csv-file

None of the previous answers were valid for me (for different reasons).以前的答案都对我无效(出于不同的原因)。

Thus, I created my own generic PHP function for it.因此,我为它创建了自己的通用 PHP 函数。 It can be either included in a CodeIgniter helper (recommended), or as a private function of any CodeIgniter class, such as a Controller:它可以包含在 CodeIgniter 帮助器中(推荐),也可以作为任何 CodeIgniter 类的私有函数,例如控制器:

/*
 *  _array2csvstr()
 *  Array to string of comma-separated-values
 */

private function _array2csvstr(array $fields)
{
    $handler = fopen('php://memory', 'r+');
    if (fputcsv($handler, $fields) === false) {
        return false;
    }
    rewind($handler);
    $csv_string = stream_get_contents($handler);
    return rtrim($csv_string);
}

I take advantage of fputcsv() php function in memory, without the need of storing any file in the filesystem.我利用内存中的fputcsv() php 函数,而无需在文件系统中存储任何文件。

Whilst yes, fputcsv is available it feels overkill even for the examples they provide (albeit the \n in my solution would negated).虽然是的, fputcsv是可用的,但即使对于它们提供的示例,它也感觉有点矫枉过正(尽管我的解决方案中的\n会被否定)。

The example below assumes Codeigniter 4 and uses the native headers option rather than the default PHP ones.下面的示例假定Codeigniter 4并使用本机标头选项而不是默认的 PHP 选项。 implode() seems perfectly sufficient for basic array rows. implode() 对于基本的数组行来说似乎已经足够了。

$this->response->setHeader('Content-Type','text/csv');
$this->response->setHeader('Content-Disposition','attachment; filename="'.$jobNo.'.csv"');

echo "\xEF\xBB\xBF"; // UTF-8 BOM

foreach ($list as $row){
    echo implode(',',$row)."\n";
}

Without the BOM (solution found here: How can I output a UTF-8 CSV in PHP that Excel will read properly? ) this code didn't work but with it, my program (LibreOffice) correctly identified the content.没有 BOM(此处找到的解决方案: How can I output a UTF-8 CSV in PHP that Excel will read correctly? )这段代码不起作用,但有了它,我的程序(LibreOffice)正确识别了内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM