使用PDO通过浏览器将MySQL表中的数据存储为CSV

时间:2022-02-24 16:40:08

I have a form that writes data to a MySQL database. I want the user to be able to download their data in CSV format after final submission.

我有一个将数据写入MySQL数据库的表单。我希望用户能够在最终提交后以CSV格式下载他们的数据。

My code is currently dumping the contents of the database into the browser, i.e. it is being written to the page, rather than to a csv file. I would like to send them to a link and be given the option to download a file.

我的代码目前正在将数据库的内容转储到浏览器中,即它正被写入页面,而不是写入csv文件。我想将它们发送到链接并获得下载文件的选项。

Here is my current code:

这是我目前的代码:

$dbo = new PDO('mysql:host=localhost;dbname=db1', $username, $password);
$sql = "SELECT * FROM table1";
$qry = $dbo->prepare($sql);

// Execute the statement
$qry->execute();
var_dump($qry->fetch(PDO::FETCH_ASSOC));
$data = fopen('/tmp/db_user_export_".time().".csv', 'w');
while ($row = $qry->fetch(PDO::FETCH_ASSOC))
{
    echo "Success";
    // Export every row to a file
    fputcsv($data, $row);
}

The current result is a page with a dump of all the data from the table. No file is being created in the location desired. Where am I going wrong?

当前结果是一个页面,其中包含表中所有数据的转储。没有在所需位置创建文件。我哪里错了?

1 个解决方案

#1


2  

The client doesn't know it is a CSV file (it's just text after all!).

客户端不知道它是一个CSV文件(毕竟它只是文本!)。

Try to add this BEFORE any output (at the top of your script):

尝试在任何输出之前添加此内容(在脚本的顶部):

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

Basically, you're telling the client/browser that the data you will be sending a CSV file.

基本上,您告诉客户端/浏览器您将发送CSV文件的数据。

That should work.

这应该工作。

You can find more information about headers there: http://php.net/manual/en/function.header.php

您可以在那里找到有关标题的更多信息:http://php.net/manual/en/function.header.php

#1


2  

The client doesn't know it is a CSV file (it's just text after all!).

客户端不知道它是一个CSV文件(毕竟它只是文本!)。

Try to add this BEFORE any output (at the top of your script):

尝试在任何输出之前添加此内容(在脚本的顶部):

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

Basically, you're telling the client/browser that the data you will be sending a CSV file.

基本上,您告诉客户端/浏览器您将发送CSV文件的数据。

That should work.

这应该工作。

You can find more information about headers there: http://php.net/manual/en/function.header.php

您可以在那里找到有关标题的更多信息:http://php.net/manual/en/function.header.php