Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript and PHP export data to file

Tags:

javascript

php

I have a button. By clicking the button, I want to export some data shown on the webpage to a file for downloading.

I am doing this in this way: I have a export.php. I send the data as the parameter to PHP file (another parameter is filename), and PHP server create a file and write the data, and then send file. Code is like:

$filename = $_GET['filename'] . '.csv';
$export = $_GET['export'];
$writer = fopen($filename, 'w') or die('cannot create');
fwrite($writer, $export . "\n");
fclose($writer);

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.basename($filename));
readfile($filename);
unlink($filename);

exit();

For cases that the data are short, it works fine. But if the data are long, since the data are passed as part of the URL, I will get "Request-URI Too Large" error.

Is there any alternative way to do that? Is it possible to directly write data using JavaScript?

like image 741
DrXCheng Avatar asked Sep 29 '26 03:09

DrXCheng


2 Answers

It sounds like you are sending to export.php with a GET, when you should be using a POST. GET is limited to 2048 characters, while a POST is not limited.

like image 195
Aaron Dougherty Avatar answered Sep 30 '26 16:09

Aaron Dougherty


You'll need to POST the data to the server. Change the METHOD in your FORM tag to POST (in your html not your php code).

Each browser limits the size of the query string / length of the URL and the limit is browser dependent. You can POST a very large amount of data to the server however. The only limit is how fast is the user's upstream bandwidth and their patience.

like image 35
Andy Jones Avatar answered Sep 30 '26 16:09

Andy Jones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!