'PHP Export CSV from MySQL Database Table

I am using a PHP script attempting to export a .csv file from values in a MySQL database. Instead of producing a .csv for download all of the values are being displayed as one long comma separated string in my browser.

Can anyone offer suggestions on how I can get this to work properly.

The script is below:

 <?php
 // Database configuration
 $dbHost     = " ";
 $dbUsername = " ";
 $dbPassword = " ";
 $dbName     = " ";

 // Create database connection
 $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

 // Check connection
 if ($db->connect_error) {
     die("Connection failed: " . $db->connect_error);
 }


 // Fetch records from database
 $query = $db->query("SELECT * FROM customers");

if($query->num_rows > 0){
     $delimiter = ",";
     $filename = "export_csv_" . date('Y-m-d') . ".csv";

// Create a file pointer
$f = fopen('php://memory', 'w');



// Set column headers
$fields = array('Name', 'Meal 1', 'Meal 2', 'Meal 3', 'Meal 4', 'Meal 5', 'Meal 6', 'Meal 7', 'Meal 8', '# of Meals', 'Meal Omission', 'Bars', 'Pancakes', '+ Bars', '+ Pancakes', 'Protein Cookies', 'Total Items');
fputcsv($f, $fields, $delimiter);

// Output each row of the data, format line as csv and write to file pointer
while($row = $query->fetch_assoc()){

    $lineData = array($row['name'], $row['meal1'], $row['meal2'], $row['meal3'], $row['meal4'], $row['meal5'], $row['meal6'], $row['meal7'],$row['meal8'], $row['num_of_meals'], $row['mealomission'], $row['bars'], $row['pancakes'], $row['bars_plus'], $row['pancakes_plus'], $row['protein_cookies'], $row['total_items']);
    fputcsv($f, $lineData, $delimiter);
}

// Move back to beginning of file
fseek($f, 0);

// Set headers to download file rather than displayed
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');

//output all remaining data on a file pointer
fpassthru($f);
}
exit;

 ?>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source