0

Is it possible to do download a string variable in my code as a file with cakephp ?

For example:

$myString = "value1;value2;value3\n1;2;3";

I want to download the string $myString as a csv file without saving it on my server. I just want the user to be able to download the string as a file.

If you have regular php solutions, It can do the job but I prefer to use CakePHP.

Thanks for your help,

Antoine

A.Le Floch
  • 131
  • 1
  • 8
  • No idea about cakePHP but this is [trivial in standard PHP](https://stackoverflow.com/questions/4249432/export-to-csv-via-php) – Martin Apr 26 '18 at 17:54
  • I don't know cake, but Google on "force download php" and you'll get the gist. It's basically just setting some headers and echoing your variable. There isn't really much magic too it. – M. Eriksson Apr 26 '18 at 18:09
  • 2
    Please try to search and read the documentation... https://book.cakephp.org/3.0/en/controllers/request-response.html & https://book.cakephp.org/3.0/en/controllers/request-response.html#sending-a-string-as-file There is a section about what you want including examples. – floriank Apr 26 '18 at 18:41
  • probably duplicate of https://stackoverflow.com/questions/20391257/how-to-use-cakephp-export-txt-file – Peshraw H. Ahmed Apr 26 '18 at 19:49

2 Answers2

1

You have tagged this question with cakephp 2.0

As burzum points out they have an example exactly for this use case of yours here

Sending a string as a file

Ilie Pandia
  • 1,829
  • 14
  • 16
0

Work in Cakephp 3.7

$body = $this->response->getBody();
$body->write('"your", "text"');

$body = $this->response->withBody($body)->withCharset('windows-1251')->withType('text/csv');

return $this->response->withDownload('yourFileName.csv');
J_D
  • 740
  • 8
  • 17