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

enyaitl3  于 2023-01-15  发布在  其他
关注(0)|答案(6)|浏览(165)
$Data[] = array('x'=> $x, 'y'=> $y, 'z'=> $z, 'a'=> $a);

我想将此数组导出为CSV。我正在使用CodeIgniter。

w9apscun

w9apscun1#

您可以尝试使用此代码将阵列导出到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;
        }
}

希望对你有帮助。

wqlqzqxt

wqlqzqxt2#

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

zf9nrax13#

此解决方案对我有效,您必须使用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; 
  }
vlurs2pr

vlurs2pr4#

最佳用途是使用csv_from_result()
它允许您从查询结果生成CSV文件。该方法的第一个参数必须包含查询的结果对象。

$this->load->dbutil();

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

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

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

xxslljrj

xxslljrj5#

前面的答案对我来说都无效(原因各不相同)。
因此,我为它创建了自己的PHP通用函数。它可以包含在CodeIgniter helper中(推荐),也可以作为任何CodeIgniter类的私有函数,例如Controller:

/*
 *  _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);
}

我在内存中利用了fputcsv() php函数,而不需要在文件系统中存储任何文件。

bnl4lu3b

bnl4lu3b6#

虽然是的,fputcsv是可用的,但即使对于他们提供的示例来说,也感觉有些过头了(尽管我的解决方案中的\n会被否定)。
下面的例子假设Codeigniter 4,并使用原生头选项而不是PHP默认的头选项。内爆()似乎完全足以处理基本的数组行。

$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";
}

没有BOM(解决方案可在此处找到:How can I output a UTF-8 CSV in PHP that Excel will read properly?)这段代码不起作用,但我的程序(LibreOffice)正确识别了内容。

相关问题