-2

Is it possible to create a download form data to local machine without writing it to a file one the server?

I want to click export button on form and have "save as" file dialog popup, that would let me save the form data to my local machine with a view to upload it back to server at some later stage. I want to do this without saving the form data to a file on the server and then downloading it.

I have encoded form data into json format. $json_data=json_encode($data); I just can't find a way to download this without writing it to a file on the server first.

Nigel
  • 135
  • 7

1 Answers1

1

I just can't find a way to download this without writing it to a file on the server first.

It's actually kind of the opposite: if you look at any instructions on using PHP to send a download, such as Force file download with php using header() you will see that the actual content of the file needs to be read and echoed to the browser. Often this is done with the convenient function readfile, but this is just a more efficient version of echo file_get_contents($filename);

If you have some content in a string, and you echo it, the browser has no way of knowing whether you wrote it to a file on your server first; it sees the exact same output. The thing that it will look at to decide whether to display it or prompt to save is the headers, particularly the Content-Type and Content-Disposition headers.

IMSoP
  • 89,526
  • 13
  • 117
  • 169
  • I was getting html embedded along with the json data. I had to add ob_clean(); ob_start(); – Nigel Jul 10 '23 at 14:35
  • @Nigel While cleaning the output buffer is a workaround, a better solution is to change your code so that it doesn't echo that HTML in the first place. That might be a case of making sure all your "business logic" (deciding what to do, preparing data) is done separately from, and before, your "presentation logic" (deciding how to show it, including things you _nearly_ always want, like echoing a page header). That way you're not telling PHP to prepare some HTML then throw it away again, and the code will ultimately be easier to follow and more flexible. – IMSoP Jul 10 '23 at 15:35