Jump to content

Having problem exporting CSV


spoco

Recommended Posts

Hello. I am trying to export a CSV file from a MySQL database using PHP. The following code returns all of the data and displays it, but does not export it. Any suggestions?

<?php require_once("databaseconn.php"); ?>
<?php
mysql_select_db('training', $databaseconn) or die('Could not select database');
function parseCSVComments($comments) {
  $comments = str_replace('"', '""', $comments); // First off escape all " and make them ""
  if(eregi(",", $comments) or eregi("\n", $comments)) { // Check if I have any commas or new lines
    return '"'.$comments.'"'; // If I have new lines or commas escape them
  } else {
    return $comments; // If no new lines or commas just return the value
  }
}

$sql = mysql_query("SELECT * FROM evaluation"); // Start our query of the database
$numberFields = mysql_num_fields($sql); // Find out how many fields we are fetching

if($numberFields) { // Check if we need to output anything
for($i=0; $i<$numberFields; $i++) {
	$head[] = mysql_field_name($sql, $i); // Create the headers for each column, this is the field name in the database
}
$headers = join(',', $head)."\n"; // Make our first row in the CSV

while($info = mysql_fetch_object($sql)) {
	foreach($head as $fieldName) { // Loop through the array of headers as we fetch the data
		$row[] = parseCSVComments($info->$fieldName);
	} // End loop
	$data .= join(',', $row)."\n"; // Create a new row of data and append it to the last row
	$row = ''; // Clear the contents of the $row variable to start a new row
}
// Start our output of the CSV
header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=evaluation.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $headers.$data;
} else {
// Nothing needed to be output. Put an error message here or something.
echo 'No data available for this CSV.';
}
?>

 

 

Link to comment
https://forums.phpfreaks.com/topic/133499-having-problem-exporting-csv/
Share on other sites

Instead of

 

header("Content-type: application/x-msdownload");

  header("Content-Disposition: attachment; filename=evaluation.csv");

  header("Pragma: no-cache");

  header("Expires: 0");

 

 

TRY

 

header("Content-type: application/octet-stream");

header("Content-Disposition: attachment; filename=evaluation.xls");

header("Pragma: no-cache");

header("Expires: 0");

 

AND I would rather you use variables for clearer and professional coding's sake

 

$filename = 'evaluation.xls';

 

header("Content-type: application/octet-stream");

header("Content-Disposition: attachment; filename=".$filename);

header("Pragma: no-cache");

header("Expires: 0");

 

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.