且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用fputcsv php在csv上添加标题

更新时间:2023-09-18 23:02:52

如果您打算使用它来创建可以用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.