Force Download CSV File

后端 未结 3 1592
半阙折子戏
半阙折子戏 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);
    }
    
    0 讨论(0)
  • 2020-12-06 11:04

    Put this code below your loop.

    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="pedidos.csv"');
    
    echo $shtml;
    

    How did you find out the content type application/force-download? I've never heard of it. The proper MIME type for CSV is text/csv

    You can find more examples how to use header function in php manual

    You need also display $shtml you didn't do it in your code.

    0 讨论(0)
  • 2020-12-06 11:17

    you need to echo your content after the header

    header('Content-Description: File Transfer');
    header('Content-Type: application/force-download');
    header('Content-Disposition: attachment; filename=pedidos.csv');
    echo $shtml
    
    0 讨论(0)
提交回复
热议问题