无法从下载助手代码点火器 3.0 创建 .csv 文件

unable to create .csv file from Download helper code igniter 3.0

我正在尝试使用以下代码将列表页面导出到 csv 文件。

 public function export()
{
    $customers = \CI::Customers()->get_customer_export();

    \CI::load()->helper('download_helper');
    force_download('customers.csv', ($customers));
}

如果我尝试 json_encode $customers 变量,它会生成第二个参数应该是字符串而不是任何字符串的错误 array.Also,它会创建一个文件但输出 json 代码csv 文件。

感谢任何帮助

尝试使用这个函数:首先你已经把这段代码放在 helper 中:

function array_to_csv($array, $download = "")
{   
    if ($download != "")
    {    
        header('Content-Description: File Transfer');
        header("Content-type: application/vnd.ms-excel");
        header('Content-Disposition: attachement; filename="' . $download . '"');
        header('Content-Transfer-Encoding: binary');
    }        

    ob_start();
    $f = fopen('php://output', 'w') or show_error("Can't open php://output");
    $n = 0;        
    foreach ($array as $line)
    {
        $n++;
        if ( ! fputcsv($f, $line))
        {
            show_error("Can't write line $n: $line");
        }
    }
    fclose($f) or show_error("Can't close php://output");
    $str = ob_get_contents();
    ob_end_clean();

    if ($download == "")
    {
        return $str;    
    }
    else
    {    
        print "\xEF\xBB\xBF"; // UTF-8 BOM
        print $str;
    }        
}

阵列形成应该是这样的:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 0
            [2] => Test 1
        )

    [1] => Array
        (
            [0] => 2
            [1] => 1
            [2] => Test 1.1
        )

    [2] => Array
        (
            [0] => 3
            [1] => 1
            [2] => Test 1.2
        )

)

为了简单起见,您也可以使用 'CI database utility class',如下所示:

$this->load->dbutil(); 
$query = $this->db->query("SELECT * FROM mytable"); 
echo $this->dbutil->csv_from_result($query);

查看下面的用户指南了解更多信息https://www.codeigniter.com/userguide3/database/utilities.html