繁体   English   中英

如何在 PHP 中分隔 CSV 标题和列

[英]How do I seperate CSV headers and columns in PHP

我正在尝试使用 PHP 创建一个 csv,它将标题和列分开。

目前我能够创建 csv 并转储数据,但每一行都转储到一个单元格中。

结果是: 在此处输入图像描述

我期待这个:

在此处输入图像描述

这是我的代码

<?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 是对的。 Excel 在打开 CSV 文件时有点愚蠢,尤其是带有逗号分隔符的文件(讽刺的是)。 您的文件看起来不错,但如果您需要在 Excel 中自动打开它(其他人需要打开它),您可能希望找到哪个是 Excel 的默认分隔符并在脚本中设置它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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