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. 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.



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";
            $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";




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.

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.

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"');

Need Your Help

Why does Console.WriteLine() block in callback from Stream.ReadAsync()?

c# io console

I have a callback function in which I am trying to write the data that I read in an overriden ReadAsync().

Programmatically sending mule message (formerly: Accessing mule http endpoint from java)

java mule

Scroll towards the end for the solution to the topic's problem. The original question was asking for a somewhat different thing.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.