Force Download CSV File

后端 未结 3 1591
半阙折子戏
半阙折子戏 2020-12-06 10:35

I am trying to create a button that will force a CSV file download but for some reason I am not able to get it working. This is the code that I have:

public          


        
3条回答
  •  时光取名叫无心
    2020-12-06 11:00

    Well. you may try this, it'll work if your result is not empty

    public function export_to_csv($result)
    {
        if(!$result) return false;
        ob_end_clean();
        header( 'Content-Type: text/csv' );
        header( 'Content-Disposition: attachment;filename=pedidos.csv');
        $fp = fopen('php://output', 'w');
        $headrow = $result[0];
        fputcsv($fp, array_keys($headrow));
        foreach ($result as $data) {
            fputcsv($fp, $data);
        }
        fclose($fp);
        $contLength = ob_get_length();
        header( 'Content-Length: '.$contLength);
    }
    

提交回复
热议问题