问题是使用 Symfony 的转发功能将数据从一个控制器发送到另一个控制器。 该功能的解释这里
在我的第一个控制器中,我执行由操作员提供的日期限制的查询。
#[Route('/admin/fuente/exportar0/', name: 'app_exportar0_fuente', methods: ['GET', 'POST'])]
public function exportar0(Request $request, FuenteRepository $fuenteRepository, CSVResponse $CSVResponse): Response
{
$defaultData = [];
$form = $this->createFormBuilder($defaultData, ['method' => Request::METHOD_GET])
->add('fecha_desde', DateType::class, array(
'label' => 'Fecha desde?: ',
'input'=>'string', 'required' => true,
'widget' => 'single_text',
'attr' => array('style' => 'width: 120px'),
))
->add('fecha_hasta', DateType::class, array(
'label' => 'Fecha hasta?: ',
'input'=>'string', 'required' => true,
'widget' => 'single_text',
'attr' => array('style' => 'width: 120px'),
))
->add('save', SubmitType::class, ['label' => 'Buscar'])
->getForm();
$form->handleRequest($request);
if($form->isSubmitted()&&$form->isValid()){
// datafecha is an array with "fecha_desde", and "fecha_hasta" keys
$datafechas = $form->getData();
$noticias = $fuenteRepository->findTodosCSV($datafechas);
$response = $this->forward('App\Controller\FuenteController::csvAction', [
'noticias' => $noticias
]);
return $response;
}
return $this->render('fuente/entrefechas.html.twig', array(
'form' => $form->createView() ));
}
在第二个控制器中,我使用前一个控制器的查询结果生成 csv 文件并下载它。
#[Route('/admin/fuente/csv/', name: 'app_csv_fuente', methods: ['GET', 'POST'])]
public function csvAction(array $noticias ): Response
{
$data=array();
$data[0]= array("Id","Diario","Link", "Palabras","Título","Contenido","Fecha","Mes", "Año",
"Protagonista", "Dinámica Conflictual", "Sector", "Sub sector", "Departamento","Pertenencia",
"Agrupación", "Agregación", "Antagonista", "Actor Estatal","Nivel de Gobierno", "Participación",
"Protagonista", "Respuesta Patronal 1","Respuesta Patronal 2", "Respuesta Estado 1", "Respuesta Estado 2",
"Demanda 1 nombre", "Demanda 1 principal","Demanda 2 nombre","Demanda 2 principal",
"Demanda 3 nombre", "Demanda 3 principal", "Actor emergente",
"Formato","Formato 2","Formato 3",
);
$i=1;
foreach ($noticias as $noticia) {
$data[$i]= array(
$noticia['id'],
$noticia['diario'],
$noticia['link'],
$noticia['palabras'],
$noticia['titulo'],
$noticia['contenido'],
$noticia['fecha']->format('d-m-Y'),
$noticia['fecha']->format('F'),
$noticia['fecha']->format('Y'),
$noticia['protagonista_name'],
$noticia['actividad_name'],
$noticia['sector_name'],
$noticia['subsector_name'],
$noticia['Departamento'],
$noticia['Pertenencia'],
$noticia['Agrupacion'],
$noticia['Agregacion'],
$noticia['Antagonista'],
$noticia['Actorestatal'],
$noticia['Nivelgobierno'],
$noticia['Participacion'],
$noticia['protagonista_name'],
$noticia['respuestapatronal_name'],
$noticia['respuestapatronal1_name'],
$noticia['respuestaestado_name'],
$noticia['respuestaestado1_name'],
$noticia['demanda1_name'],
$noticia['principal1_name'],
$noticia['demanda2_name'],
$noticia['principal2_name'],
$noticia['demanda3_name'],
$noticia['principal3_name'],
$noticia['Actoremergente'],
$noticia['protesta_name'],
$noticia['protesta_name2'],
$noticia['protesta_name3'] ,
);
$i++;
}
$fp = fopen('php://memory','w', "w");
foreach($data as $fields){
fputcsv($fp, $fields, ';');
}
rewind($fp);
$response = new Response(stream_get_contents($fp));
fclose($fp);
$response->headers->set('Content-Type', 'text/csv; charset=UTF-8');
$response->headers->set('Content-Encoding', 'UTF-8');
$response->headers->set('Cache-Control', 'private');
$response->headers->set('Content-Disposition', 'attachment; filename="noticias.csv"');
$response->sendHeaders();
return $response;
}
问题是下载失败但csv文件创建了! 当我将此函数应用于下载时,它不会发生,但文件会在内存或服务器空间中的某个位置生成。我怎么知道? 如果我在底部工具栏中查找 Ajax 部分,我可以看到已生成但未下载的文件列表。 如果我们点击功能栏中的其中一些链接,就可以在那里实现下载。 挑战在于如何实现直接下载
如果您稍后想要获取内容,您还需要打开流进行阅读。
$fp = fopen('php://memory','rw');
foreach($data as $fields){
fputcsv($fp, $fields, ';');
}
rewind($fp);
$response = new Response(stream_get_contents($fp));
fclose($fp);