mardi 27 mars 2018

didn't download .csv in laravel (php)?

I am new in laravel, when I hit my code then it's given response in browser like output: ID,"Event Name" 1,"test event" 3,"test test 1"

please see my below code and guide me =>

$events = Events::all()->toArray();
        $event_set = array();

        //echo '<pre>'; print_r($events); die;
        $i =0;
        foreach ($events as $event)
        {
            $record['id'] = $event['id'];
            $record['event_name'] = $event['event_name'];
            $event_set[$i] = $record;
            $i++;
        }

        //echo '<pre>'; print_r($event_set); die('test');
        $filename = "events.csv";

        $header = ['ID', 'Event Name'];
        $export_data = $this->getDataCsv($event_set, $header);
        return response($export_data)
            ->header('Content-Type','application/csv')
            ->header('Content-Disposition', 'attachment; filename="'.$filename.'"')
            ->header('Pragma','no-cache')
            ->header('Expires','0');


function getDataCsv($data, $headers, $delimiter = ',', $enclosure = '"') {


        $filename = "php://temp";
        $fp = fopen($filename, 'w');
        fputcsv($fp, $headers, $delimiter, $enclosure);
        if(count($data)>0){
            foreach ($data as $key => $value) {
                fputcsv($fp, $value, $delimiter, $enclosure);
            }
        }
        rewind($fp);
        $csvdata = fread($fp, 1048576);
        fclose($fp);
        return rtrim($csvdata, "\n");
    }

please suggest me, what I doing wrong ?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire