mysql导出csv科学基数,从Mysql导出CSV

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

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

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 'Download Exported Data'; //want my link to go in here...

print "$header\n$data";

解决方案

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.

For example, you could have Click here to download CSV, 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值