0

I wrote an API call that saves and exports data to csv file in my Symfony project but I have trouble figuring out how to return the API caller response with download.

I want it to be like:

http://path.to.the.server/web/uploads/path/to/the/file.csv

My code:

 // get directory path to save csv files
    $rootDir = $this->container->get('kernel')->getRootDir();
    $dir = $rootDir . '/../web/uploads/';

    // make new directory by date
    if(!is_dir($dir)) {
        mkdir($dir, 0777, true) || chmod($dir, 0777);
    }

    // generating csv file name
    $fileName = 'name-'.date('Y-m-d').'.'.csv';
    $fp = fopen($dir . $fileName, 'w');

    // prepare data for exporting
    $getResults = $this->getMyData();
    $pullResults = json_decode($getResults);
    $results = $pullResults->data->items;

    $rows = [];

    $rows[] = array(
        "First Name",
        "Last Name"
    );

    foreach ($results as $row) {
        $rows[] = array(
            $row->firstName,
            $row->lastName
        );
    }

    foreach ($rows as $row) {
        fputcsv($fp, $row);
    }

    fclose($fp);

    return $this->success();

Any suggestions?

develops
  • 279
  • 1
  • 5
  • 14
  • Take a look at: https://stackoverflow.com/questions/13010411/symfony2-force-file-download – FMK May 07 '19 at 08:41
  • You have a syntax error this `$fileName = 'name-'.date('Y-m-d').'.'.csv';` should be `$fileName = 'name-'.date('Y-m-d').'.csv';` – executable May 07 '19 at 08:41
  • Possible duplicate of [Symfony2 - Force file download](https://stackoverflow.com/questions/13010411/symfony2-force-file-download) – FMK May 07 '19 at 08:41
  • Thanks. I'll take a look. @FMK – develops May 07 '19 at 08:42
  • As I used suggested post it throws error ""Warning: mime_content_type(name-2109-05-07.csv): failed to open stream: No such file or directory". But the csv file is located in directory. @FMK – develops May 07 '19 at 08:53
  • You could use a streaming response: https://symfony.com/doc/current/components/http_foundation.html#streaming-a-response – FMK May 07 '19 at 08:55
  • Thank you. I will post my solution! @FMK – develops May 07 '19 at 09:19

1 Answers1

0

This did it for me:

$response = new BinaryFileResponse($dir .DIRECTORY_SEPARATOR. $fileName);

    $d = $response->headers->makeDisposition(
        ResponseHeaderBag::DISPOSITION_ATTACHMENT,
        $fileName
    );

    $response->headers->set('Content-Disposition', $d);

    return $response;

Source: documentation

develops
  • 279
  • 1
  • 5
  • 14