简体   繁体   English

使用php将mysql查询导出到可下载的.csv文件

[英]Using php to export a mysql query to a downloadable .csv file

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. 我有一个链接设置将我的表导出为可下载的.csv文件。 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. 当我单击链接时代码以csv格式转储表,但是它不是作为附件加载它只是在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?>

-- -

My results how up as 我的结果怎么样

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. A,B,C,D,A,B,C,D - 我不知道为什么当我点击我的链接(download.php?action = download)时不会提示我将文件保存到我的硬盘而不是仅仅在页面上显示信息。

Any help would be very appreciated! 任何帮助将非常感谢!

Use before sending the output: 在发送输出之前使用:

header('Content-Disposition: attachment; filename="downloaded.csv"');

See: Create a CSV File for a user in PHP - For more details. 请参阅: 在PHP中为用户创建CSV文件 - 有关详细信息。

Try this, works for me: 试试这个,对我有用:

header("Content-Type: text/csv");
header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
header("Content-Transfer-Encoding: binary\n");
header('Content-Disposition: attachment; filename="downloaded.csv"');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM