0

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!

Burhan Ali
  • 2,258
  • 1
  • 28
  • 38
snapplex
  • 851
  • 3
  • 13
  • 27
  • So...I figured out why out of the 20+ examples I tried I could not get the download to work. Apparently you have to have a blank php file. Meaning there should only be php code and no html. As soon as I did that all the header features worked w/o a problem. Thanks for the help everyone. – snapplex Dec 22 '11 at 02:04

2 Answers2

1

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.

Community
  • 1
  • 1
check123
  • 1,989
  • 2
  • 22
  • 28
1

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"');
Oldskool
  • 34,211
  • 7
  • 53
  • 66