使用php将mysql查询导出为可下载的.csv文件
我已经尝试了我的判断,以避免提出这个问题(我在论坛上已经看过并尝试了大量的例子),大部分工作让我相信我错过了一些事情。我有一个链接设置将我的表导出为可下载的.csv文件。当我单击链接代码以csv格式转储表时,BUT而不是作为附件加载,它只显示html中的表的内容。
I've tried my darnest to avoid asking this question (I viewed and try a ton of examples already on the forum), most partially work which leads me to believe I'm missing something. I have a link setup to export my table into a downloadable .csv file. When I click the link the code dumps the table in csv format, BUT instead of it loading as an attachment it just displays the contents of the table in html.
-
<?php
include('bikes.php'); //db connection settings
if ($_GET['action'] == 'download')
{
header('Content-Disposition: attachment; filename="downloaded.csv"');
$query = "SELECT * FROM bikes";
$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";
}
print "$header\n$data";
}
exit();
php?>
-
我的结果如何
A,B,C,D,A ,B,C,D - 我不知道为什么当我点击我的链接(download.php?action = download),这不是提示我将文件保存到我的硬盘驱动器,而不是只显示在
A, B, C, D, A, B, C, D -- I have no idea why when I click my link (download.php?action=download) that is does not prompt me to save the file to my hard drive, instead of just displaying the information on the page.
任何帮助将非常感谢!
使用在发送输出之前:
header('Content-Disposition: attachment; filename="downloaded.csv"');
请参阅:为PHP中的用户创建CSV文件 - 有关详细信息。
See: Create a CSV File for a user in PHP - For more details.