简体   繁体   中英

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: 在此处输入图像描述

I expected this:

在此处输入图像描述

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; 

@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 (ei 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM