使用 fputcsv 在 csv 上添加标题 php

Add heading on csv using fputcsv php

我正在尝试将一些数据输入到一个 csv 文件中,它运行良好,但是如果我尝试添加数据 table 的 header,则 Excel 不会'不要让我打开文件,因为 "the file format and extension of file.csv don't match. the file could be corrupted or unsafe".

代码如下:

//crate headers
$headers[] = "ID";
$headers[] = "Name";
$headers[] = "Ref";
$headers[] = "Quantity";

// crete and open file  
$csvName = "file.csv";
$fileHandle = fopen($csvName, 'w') or die('Can\'t create .csv file, try again later.');

//Add the headers, if I take this line out the excel allows me to open the file
fputcsv($fileHandle,$headers,";");

//Add the data
for($i = 0; $i < count($info); ++$i) {
    fputcsv($fileHandle,$info[$i],";");
}

//close file
fclose($fileHandle);

编辑:

这是我用记事本打开的 csv 的第一行:

编号;名称;编号;数量

2;"Blouse - Color : White, Size : M";demo_2;6

3;"Printed Dress - Color : Orange, Size : S";demo_3;4

尝试将您的 headers 更改为:

$headers[] = '"ID"';
$headers[] = '"Name"';
$headers[] = '"Ref"';
$headers[] = '"Quantity"';

这会将字符串用双引号引起来,这应该可以解决您遇到的语法问题。

Excel 很挑剔。 PHP 默认使用逗号,这实际上是您想要用于 Excel 的逗号。分号通常会起作用,但不是默认值 - 请记住,CSV 代表 逗号 分隔值。第二个问题是 Excel 特有的。尽管它在数据部分处理不带引号的字符串很好,但出于某种原因,它在 header 行上效果不佳。我在 fputcsv 中没有看到强制引号的选项,因此您需要对它们进行硬编码。类似于:

// create and open file  
$csvName = "file.csv";
$fileHandle = fopen($csvName, 'w') or die("Can't create .csv file, try again later.");

//Add the headers - note that \r\n or \n is OS dependent
fwrite($fileHandle,'"ID","Name","Ref","Quantity"' . "\r\n");

//Add the data
for ($i = 0; $i < count($info); ++$i) {
    fputcsv($fileHandle,$info[$i]);
}

//close file
fclose($fileHandle);

如果您打算使用它来创建可以使用 Excel 正常打开的 CSV 文件,则 header 不需要用双引号引起来(因为它们不包含任何分隔符),您应该使用逗号而不是分号作为分隔符。但是,如果您进行了这些更改,当您尝试使用 Excel 打开生成的文件时,您仍然会收到相同的错误消息。令人惊讶的是,这是 because your headers start with 'ID'.

如果您可以为第一列使用不同的名称 header,它可以稍微简化一些事情。

$headers = ["ItemID", "Name", "Ref", "Quantity"];

$csvName = "file.csv";
$fileHandle = fopen($csvName, 'w') or die('Can\'t create .csv file, try again later.');

//Add the headers
fputcsv($fileHandle, $headers);

//Add the data
foreach ($info as $item) {
    fputcsv($fileHandle, $item);
}

//close file
fclose($fileHandle);

这应该创建一个 .csv 文件,该文件将在 Excel 中打开且没有错误。