简体   繁体   中英

Javascript and PHP export data to file

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?

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.

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.

Instead of passing the data as a query string, use javascript to create an iframe and build a form which then posts to the php file.

IF your using jquery there's a good tutorial http://tutorialzine.com/2011/05/generating-files-javascript-php/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM