从Mysql导出CSV [英] Export CSV from Mysql

查看:68
本文介绍了从Mysql导出CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

导出使用php从我的mysql表之一创建的csv文件时遇到麻烦.

I'm having a bit of trouble exporting a csv file that is created from one of my mysql tables using php.

我正在使用的代码可以打印正确的数据,但是我看不到如何在csv文件中下载此数据,也没有提供指向已创建文件的下载链接.我以为浏览器应该会自动提供要下载的文件,但事实并非如此. (可能是因为以下代码是使用ajax调用的?)

The code I'm using prints the correct data, but I can't see how to download this data in a csv file, providing a download link to the created file. I thought the browser was supposed to automatically provide the file for download, but it doesn't. (Could it be because the below code is called using ajax?)

任何帮助,我们将不胜感激-下面的代码是S.

Any help greatly appreciated - code below, S.

include('../cofig/config.php');    //db connection settings
$query = "SELECT * FROM isregistered";
$export = mysql_query($query) or die("Sql error : " . mysql_error());
$fields = mysql_num_fields($export);
for ($i = 0; $i < $fields; $i++) {
    $header .= mysql_field_name($export, $i) . "\t";
}
while ($row = mysql_fetch_row($export)) {
    $line = '';
    foreach ($row as $value) {
        if ((!isset($value) ) || ( $value == "" )) {
            $value = "\t";
        } else {
            $value = str_replace('"', '""', $value);
            $value = '"' . $value . '"' . "\t";
        }
        $line .= $value;
    }
    $data .= trim($line) . "\n";
}
$data = str_replace("\r", "", $data);

if ($data == "") {
    $data = "\n(0) Records Found!\n";
}
//header("Content-type: application/octet-stream"); //have tried all of these at sometime
//header("Content-type: text/x-csv");
header("Content-type: text/csv");
//header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=export.csv");
//header("Content-Disposition: attachment; filename=export.xls");
header("Pragma: no-cache");
header("Expires: 0");

echo '<a href="">Download Exported Data</a>'; //want my link to go in here...

print "$header\n$data";

推荐答案

同一页面上不能有文本和下载内容.您需要有一个指向下载区域的链接,该链接可能只是通向函数的GET参数,然后该函数执行所有处理,显示标头并回显CSV的内容.

You can't have text and a download on the same page. You need to have a link to the download area, which could just be a GET parameter leading to a function, which then does all the processing, displays headers, and echoes the content of the CSV.

例如,您可能有<a href="foo.php?action=download">Click here to download CSV</a>,然后在代码中有if ($_GET['action'] === 'download'),从数据库中获取数据,对其进行格式化,发送标题,然后回显数据.然后die(),因为脚本的那部分无法完成.

For example, you could have <a href="foo.php?action=download">Click here to download CSV</a>, then in your code have if ($_GET['action'] === 'download'), get the data from the database, format it, send the headers, and echo the data. And then die(), because that part of the script can accomplish no more.

这篇关于从Mysql导出CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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