Reputation: 851
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?>
--
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!
Upvotes: 0
Views: 15197
Reputation: 2009
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.
Upvotes: 1
Reputation: 34867
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"');
Upvotes: 1