【问题标题】:Create downloadable CSV from web search using PHP and mySQL使用 PHP 和 mySQL 从 Web 搜索创建可下载的 CSV
【发布时间】:2013-03-19 16:42:29
【问题描述】:

我正在尝试创建一个可供用户下载的 CSV 文件,并且没有将数据永久保存在服务器上。

我在这个页面上使用了 mySQL 和 PHP。我以正确的格式获取数据以在网页上显示(“回声”),但无法生成/下载文件......也许我遗漏了一些东西或在错误的地方寻找,但任何帮助都会很棒!

我一直在尝试我自己的和我找到的其他脚本,但我目前拥有的脚本如下:

$file = 'export';
$colresult = mysql_query("SHOW COLUMNS FROM ".$tbl_name.""); 

if (mysql_num_rows($colresult) > 0) {  
while ($row = mysql_fetch_assoc($colresult)){   
$csv_output .= $row['Field'].", ";   $i++;  } } $csv_output .= "\n";   

$csvresult = mysql_query($sql); 

while ($rowr = mysql_fetch_row($csvresult)) {  
for ($j=0;$j<$i;$j++) {   $csv_output .= $rowr[$j].", ";  
}  

$csv_output .= "\n"; }   
$filename = $file."_".date("Y-m-d_H-i",time()).".csv"; 
header("Content-type: application/csv"); 
header("Content-disposition: attachment;filename=".$filename.".csv"); 
readfile("../documents/csv/".$filename.".csv");

$fp = fopen($filename, 'w');
foreach($csvret as $csvret){
fputcsv($fp, $csvret);
}

print $csv_output; 
print $filename; 

谢谢!

【问题讨论】:

  • 您应该考虑如果您的数据包含逗号会发生什么
  • 桌子边上已经清理过了。主要是想获取要创建的文件并从那里进行故障排除。
  • 那么你会发现implode(',' $record);implode(',', array_keys($record));mysql_fetch_assoc();很有用

标签: php mysql export-to-csv


【解决方案1】:

您需要传递一些标头来强制网络浏览器将文件识别为“可下载”:

<?php

header('Content-Description: File Transfer');
header("Content-Type: application/csv"); 
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));

readfile($filename);
exit;

只需添加该代码代替:

print $csv_output; 
print $filename; 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-04
    • 2017-05-21
    • 2014-03-28
    • 1970-01-01
    • 1970-01-01
    • 2014-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多