我编写了一个API调用,用于将数据保存并导出到Symfony项目中的csv文件中,但是我很难弄清楚如何通过下载返回API调用者响应。
我希望它像:
我的代码:
// 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();
有什么建议吗?
答案 0 :(得分:0)
这对我有用:
$response = new BinaryFileResponse($dir .DIRECTORY_SEPARATOR. $fileName);
$d = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$fileName
);
$response->headers->set('Content-Disposition', $d);
return $response;