I am trying to print out a csv from my MySql page, but instead of creating a file, the info is getting printed to the page. here is the URL and code:

http://www.primaryperspective.org/test_export_csv.php

<?php

$dbhost = 'localhost';
$dbuser = '*';
$dbpass = '
*';

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');

$dbname = 'membertest';
mysql_select_db($dbname);

$select = "SELECT * FROM members";

$export = mysql_query ( $select ) 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";
}

header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=log.csv");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";

?>

    Found out that the PHP version on the server is < 5, so putcsv is not an option.

      There is white space before the data being printed.
      Probably a blank line before the <?php

        OK, but the goal is to export a CSV, not have it print out in a browser window.

          Any output before the headers causes problems.
          You will probably find an error message in your logs.

            Write a Reply...