简体   繁体   English

将CSV文件下载到本地下载文件夹

[英]Download CSV file to local Download's folder

I have a php file which converts the form data to csv format and then it should get downloaded automatically to the user's local download folder. 我有一个php文件,它将表单数据转换为csv格式,然后它应该自动下载到用户的本地下载文件夹。

$time = time();
$filename = 'exceldownloads/myreport_'.$time.'.csv';
$file = fopen($filename,'w');
fputcsv($file,$rowexcel);

The above code works fine and stores the csv file in the specified folder in server. 上面的代码工作正常,并将csv文件存储在服务器的指定文件夹中。 But my requirement is to download it to a local folder. 但我的要求是将其下载到本地文件夹。 I have seen many solutions to the above problem, but they are working only if we know the local destination folder. 我已经看到了上述问题的许多解决方案,但只有当我们知道本地目标文件夹时它们才能正常工作。 However, My requirement is to make it downloadable to the end-user local download's folder (whose download location Im unaware of). 但是,我的要求是将其下载到最终用户本地下载的文件夹(其下载位置我不知道)。 Is there anyway to get it downloaded on to the end user system without specifically mentioning the destination path. 无论如何都要将其下载到最终用户系统而不特别提及目标路径。

You can export the output of your web page as an attachment, which will be shown as a download to the user. 您可以将网页的输出导出为附件,该附件将显示为下载给用户。 You can do this by outputting appropriate headers right before you make any output to the user. 您可以在向用户输出任何输出之前输出适当的标题来执行此操作。

Here's an example, that creates a download of a CSV file called foo.csv: 这是一个示例,它创建了一个名为foo.csv的CSV文件的下载:

header("Content-type: text/csv");
header("Content-Disposition: attachment;Filename=foo.csv");

After outputting the headers, you just output all of the file's data to the page content. 输出标题后,您只需将所有文件的数据输出到页面内容。

* Edit: * Here's a working snippet, as requested: * 编辑:*这是一个工作片段,根据要求:

header("Content-type: text/csv");
header("Content-Disposition: attachment;Filename=foo.csv");
echo implode(";", $rowexcel) . "\r\n";  // you should expand this accordingly

alternatively, here is another snippet, based on your code: 或者,这是另一个片段,基于您的代码:

$filename = 'myreport'.time().'.csv';
$f = fopen($filename,'w');
fputcsv($f,$rowexcel);
header('Content-type: application/csv');
header('Content-Disposition: attachment;filename="'.$filename.'"');
readfile($filename);

If you are not getting any download, make sure that you don't output anything before the header() calls. 如果您没有下载任何内容,请确保在header()调用之前不输出任何内容。 Also, make sure that you don't have any UTF8 BOM bytes at the beginning of your PHP file, as these can be misinterpreted for output 另外,请确保PHP文件开头没有任何UTF8 BOM字节,因为这些字节可能会被错误解释为输出

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

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