Y
Y
Yuri Voronin2019-10-25 17:45:21
Laravel
Yuri Voronin, 2019-10-25 17:45:21

How to create a csv file on the fly and return to download?

Good afternoon.
When you click on the button, the csv file should be downloaded.
I do it via ajax. What method should be done? GET or POST?
Here is the function in the controller that is being requested via ajax

public function uploadToFile() {
....
       $orders = Order::where($arFilter)->orderBy('id', 'desc')->get();

        header('Content-Description: File Transfer');
        header("Cache-Control: public");
        header('Content-Disposition: attachement;filename="test.csv";');
        header('Content-Type: application/csv; charset=UTF-8');

        $titles = array("id", "От куда", "Куда");

        ob_start();
        $df = fopen("php://output", 'w');
        fputcsv($df, $titles, ';');
        foreach ($orders as $k => $order) {
            $arTmp = array($k, $order->fromCity, $order->toCity);
            fputcsv($df, $arTmp, ';');
        }
        fclose($df);
        $str = ob_get_clean();
}

In $str I get the text display of the file.
How can I get it to download?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Igor Vorotnev, 2019-10-25
@yuraSco

https://laravel.com/docs/5.8/responses#file-downloads

return response()->streamDownload(function () {
    echo $str;
}, 'test.csv');

G
green_goo, 2019-10-25
@green_goo

Remove ob_start();and$str = ob_get_clean();

R
raxweb, 2021-02-16
@raxweb

Here is a simple script: aceweb.ru/articles/php/export-csv.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question