duanhan7001 2017-04-06 06:36
浏览 37
已采纳

无法从下载帮助程序代码igniter 3.0创建.csv文件

I am trying to export a list page to csv file using the code below.

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

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

It generates and error that second parameter should be a string not any array.Also if i try to json_encode the $customers variable,it creates a file but outputs json code in the csv file.

Any help is appreciated

  • 写回答

2条回答 默认 最新

  • dqvzfp6468 2017-04-06 06:54
    关注

    Try to use this function: first of all you have put this code in 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 formation should be like:

    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
            )
    
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站