samedi 17 août 2019

Saving large JSON response as a CSV file

I am having some issues understanding something. I am making a call to an API that returns a large response in a JSON format. I need to save this reponse as a csv file. As such, I am running this as a Laravel queue so it does not have any timeout issues. I have the following function

protected function json2CSV($response)
{
    $headers = array(
        'Content-Type'        => 'text/csv',
        'Content-Disposition' => 'attachment; filename=test.csv'
    );

    $array = json_decode($response, true);

    $response = new StreamedResponse(function() use($array){
        // Open output stream
        $handle = fopen('php://output', 'w');

        // Set column names from the first result keys
        $keys = [];
        foreach ($array['someElement'] as $row) {
            $keys = array_merge($keys, array_keys($row));
        }
        $keys = array_unique($keys);

        fputcsv($handle, $keys, ',');

        $template = array_fill_keys($keys, null);

        foreach ($array['someElement'] as $key => $row) {
            fputcsv($handle, array_merge($template, $row));
        }

        // Close the output stream
        fclose($handle);
    }, 200, $headers);

    return $response->send();
}

Now when I execute this within the console, I can see the output to this, and it is all structured how I need it to be. However, where does it actually save the file? I can't find a file called test.csv anywhere on my server? From my understanding it should save a file using the above approach. Is this not correct?

Thanks



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2YVdyEs
via IFTTT

Aucun commentaire:

Enregistrer un commentaire