简体   繁体   English

Javascript和PHP将数据导出到文件

[英]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 . 我是这样做的:我有一个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. 我将数据作为参数发送到PHP文件(另一个参数是文件名),PHP服务器创建一个文件并写入数据,然后发送文件。 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. 但是如果数据很长,由于数据是作为URL的一部分传递的,我将得到“Request-URI Too Large”错误。

Is there any alternative way to do that? 有没有其他方法可以做到这一点? Is it possible to directly write data using JavaScript? 是否可以使用JavaScript直接写入数据?

It sounds like you are sending to export.php with a GET, when you should be using a POST. 当你应该使用POST时,听起来你正在使用GET发送到export.php。 GET is limited to 2048 characters, while a POST is not limited. GET限制为2048个字符,而POST不受限制。

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). 将FORM标签中的METHOD更改为POST(在您的HTML中不是您的PHP代码)。

Each browser limits the size of the query string / length of the URL and the limit is browser dependent . 每个浏览器限制查询字符串的大小/ URL的长度,限制取决于浏览器 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. 不要将数据作为查询字符串传递,而是使用javascript创建iframe并构建一个表单,然后发布到php文件。

IF your using jquery there's a good tutorial http://tutorialzine.com/2011/05/generating-files-javascript-php/ 如果你使用jquery有一个很好的教程http://tutorialzine.com/2011/05/generating-files-javascript-php/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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