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:
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?