How to download a csv file with symfony 4?

I’m trying to download a csv file with symfony 4.
I read the documentation.
I understood that I must normalize my objects and encode in csv.

My controller:

/**
* @Route("/export.csv", name="exportcsv", options={"expose"=true}, methods={"GET","POST"})
*
**/
public function exportcsv(){
   $datas = $this->getDoctrine()->getRepository(Object::class)-> findBy(['Event'=> $user->getEvent()]);
   $encoders = [new CsvEncoder()];
   $normalizers = array(new ObjectNormalizer());
   $serializer = new Serializer($normalizers, $encoders);
   $csvContent = $serializer->serialize($datas, 'csv'); 
   return new Response($csvContent);
}

When i try to go on this route, i can see in my browser all my datas in the good format for a csv.
For example, I have:

NameColumn1, NameColumn2, NameColumn3

Data1Column1, Data1Column2, Data1Column3

Data2Column1, Data2Column2, Data2Column3

I read that it’s the good format to create a csv file.

I would like to know I to generate the csv file.

If anyone have a solution, it would be awesome. I’m on it for a week and I’m totally lost.

Thanks.

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *