Jump to content

CSV File Creation - Header Problems


mdemetri2

Recommended Posts

Hi, so I have had some help on an other post creating a csv file from a query populating a html table on screen. The query is passed to a csv file creator, I adapted the code, but when it comes to download IE explorer complains it can't find the file or in it's current form below, opens the file as HTML and displays the data in the browser. Works find in Google Chrome, just not in IE8. Any ideas, I think it is to do with the headers and their order / content:

<?php require_once('Connections/Connection1.php'); ?>
<?php 
//create query to select as data from your table
$select = $_GET['sqlcode'];
 $dbtable = "download";
//run mysql query and then count number of fields
$export = mysql_query ( $select ) 
       or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );

//create csv header row, to contain table headers 
//with database field names
for ( $i = 0; $i < $fields; $i++ ) {
	$header .= mysql_field_name( $export , $i ) . ",";
}

//this is where most of the work is done. 
//Loop through the query results, and create 
//a row for each
while( $row = mysql_fetch_row( $export ) ) {
	$line = '';
	//for each field in the row
	foreach( $row as $value ) {
		//if null, create blank field
		if ( ( !isset( $value ) ) || ( $value == "" ) ){
			$value = ",";
		}
		//else, assign field value to our data
		else {
			$value = str_replace( '"' , '""' , $value );
			$value = '"' . $value . '"' . ",";
		}
		//add this field value to our row
		$line .= $value;
	}
	//trim whitespace from each row
	$data .= trim( $line ) . "\n";
}
//remove all carriage returns from the data
//$data = str_replace( '\r' , " " , $data );

$data = str_replace( "\r\n", "", $data);

//create a file and send to browser for user to download
//header("Pragma: public");
//header("Expires: 0");
//header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
//header("Cache-Control: private",false);
//header('Content-Disposition: attachment; filename=customreport.csv');
//header("Content-Type: application/octet-stream");

header("Content-Disposition: attachment;filename=export_".$dbtable.".csv ");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
//header("Content-Type: application/download");
header("Content-Transfer-Encoding: binary ");

print "$header\n$data";
exit;
?>
Link to comment
https://forums.phpfreaks.com/topic/277789-csv-file-creation-header-problems/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.