Skip to content
Advertisement

Build csv and upload to google drive in php (laravel 5.8)

How do I send a response()->stream() to google drive ? I’m not getting it because this method returns a class and not a file. My question is if I will need to save locally using file_put_contents() so that I can then send it to google drive

public function buildCsv($columns, $content): Closure
    {
        return function () use ($columns, $content){
            $file = fopen('php://output', 'w');
            fputcsv($file, $columns);

            foreach ($content as $item) {
                fputcsv($file, $item);
            }

            fclose($file);
        };
    }
$cb = $this->buildCsv($this->CSVColumns, $csvData);
Storage::disk('google')->put("csv-test", response()->stream($cb, 200, $headers));

On google drive my file looks like this: Google drive file

Advertisement

Answer

Try this

public function buildCsvFile($columns, $content): string
{
    $file = tmpfile();
    fputcsv($file, $columns);
    
    foreach ($content as $item) {
        fputcsv($file, $item);
    }
    $metaDatas = stream_get_meta_data($file);
    return file_get_contents($metaDatas['uri']);
}
$cb = $this->buildCsv($this->CSVColumns, $csvData);
Storage::disk('google')->put("csv-test.csv", $cb);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement