使用fputcsv php在csv上添加标题 [英] Add heading on csv using fputcsv php

查看:183
本文介绍了使用fputcsv php在csv上添加标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些数据输入到csv文件中,并且效果很好,但是如果我尝试添加数据表的标题,Excel不会让我打开文件,因为文件格式和扩展名file.csv不匹配.该文件可能已损坏或不安全."

I'm trying to input some data into a csv file and it works nicely, but if I try to add the header of the table of data Excel won't let me open the file, because "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的第一行:

Here are the first lines of my csv open with notepad:

ID;名称;引用;数量

ID;Name;Ref;Quantity

2;上衣-颜色:白色,尺寸:M"; demo_2; 6

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

3;印花连衣裙-颜色:橙色,尺寸:S"; demo_3; 4

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

推荐答案

如果您打算使用它来创建可以用Excel正常打开的CSV文件,则标题不必用双引号引起来(因为它们不包含任何分隔符),并且分隔符应使用逗号而不是分号.但是,如果进行了这些更改,当您尝试使用Excel打开生成的文件时,您仍然会收到相同的错误消息.令人惊讶的是,这是因为您的标题以"ID"开头.

If you're intending to use this to create a CSV file that can be opened normally with Excel, the headers shouldn't need to be wrapped in double quotes (because they don't contain any separator characters), and you should use commas rather than semicolons for the separators. However, if you make those changes, you'll still get the same error message when you try to open the resulting file with Excel. Surprisingly, this is because your headers start with 'ID'.

如果您可以为第一列标题使用其他名称,则可以稍微简化一下事情.

If you can use a different name for that first column header, it could simplify things a bit.

$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中打开且没有错误.

This should create a .csv file that will open in Excel with no errors.

这篇关于使用fputcsv php在csv上添加标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆