Search code examples
phpcsvfopen

How do I seperate CSV headers and columns in PHP


I am trying to create a csv with PHP, that separate the the headers and columns.

Currently I am able to create the csv and dump the data, but each row in dumped into one cell.

The result is: enter image description here

I expected this:

enter image description here

Here is my code

<?php
// Load the database configuration file 
require_once('db/connect_db.php');

//$time = date('Y-m-d:').preg_replace("/^.*\./i","", microtime(true));
    $time = date('Y-m-d');
    $dteTimetamp = date('Y-m-d');
// Fetch records from database 
    $find = $conn->prepare("SELECT School, SchoolAddress, School_Email, Principle_Name,  Reception_Number,  QuantityFingerPrintScanner, InvoiceNumber from School");
    $find->execute();
    $udonr = "$dteTimetamp" . "Request";
    //$filename = "$udonr.csv";
// Create a file pointer 
    $f = fopen(dirname(__FILE__).'/testfolder/'.$udonr.'.csv', 'w'); 
 
// Set column headers 
    $header = array('School Name', 'Contact Person', 'Contact Number', 'School Address', 'Number of scanners to deliver', 'Invoice Nuber'); 
    fputcsv($f, $header); 

// Output each row of the data, format line as csv and write to file pointer 
    while($row = $find->fetch(PDO::FETCH_ASSOC)){ 
    $lineData = array($row['School'], $row['Principle_Name'], $row['Reception_Number'], $row['SchoolAddress'], $row['QuantityFingerPrintScanner'], $row['InvoiceNumber']); 
    fputcsv($f, $lineData); 

 
// 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; 

Solution

  • @FROSIT is right. Excel is kinda dumb about opening CSV files, especially ones with comma separator (ironically). Your file looks good but if you need to have it automatically open in Excel (e.i. someone else will need to open it), you might want to find which one is the default separator for Excel and set that in your script.