通过浏览器使用PDO将MySQL表中的数据存储为CSV [英] Storing data from MySQL table as CSV using PDO via browser

查看:54
本文介绍了通过浏览器使用PDO将MySQL表中的数据存储为CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我的代码当前正在将数据库的内容转储到浏览器中,即正在将其写入页面,而不是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.

这是我当前的代码:

$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?

推荐答案

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

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

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

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");

基本上,您是在告诉客户端/浏览器要发送CSV文件的数据.

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

应该可以.

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

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

这篇关于通过浏览器使用PDO将MySQL表中的数据存储为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆