简体   繁体   English

打开PHP创建的CSV文件

[英]Opening a CSV file created by PHP

I create a CSV file using fputcsv in PHP. 我在PHP中使用fputcsv创建一个CSV文件。 File is created successfully and I can open the file in MacOS with no problem. 文件创建成功,我可以在MacOS中打开文件没有问题。 (I use Numbers in MacOS). (我在MacOS中使用Numbers)。 The problem is in Microsoft Excel, it shows all row as merged one single column. 问题出在Microsoft Excel中,它将所有行显示为合并的单个列。

I set delimiter as ";" 我将分隔符设置为“;” in the code. 在代码中。

When I check for Language and Regional Settings as told in Microsoft documentation, the delimiter is also ";". 当我在Microsoft文档中检查语言和区域设置时 ,分隔符也是“;”。

What should I also check for? 我还应该检查什么? Thank you. 谢谢。

Well this header will allow the csv format to displayed properly. 那么这个标题将允许csv格式正确显示。

 header('Content-Encoding: UTF-8');
    header('Content-type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename=filename.csv');
    echo "\xEF\xBB\xBF";

You can use this header 您可以使用此标头

The following method seems to do the trick for me. 以下方法似乎对我有用。 Microsoft Excel opens it perfectly. Microsoft Excel完美地打开它。

$filePath = '/home/user/';
$filename = 'test.csv';

$df = fopen($filePath.$filename, 'w');
fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF));
fputcsv($df, $dataColumns);
foreach ($dataArray as $dataRow) {
    fputcsv($df, $dataRow);
}
fclose($df);

// Output csv
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename='.$filename);
header("Cache-Control: no-store, no-cache");
readfile($filePath.$filename);

Notes 笔记

  • the line fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF)); fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF)); writes file header for correct encoding. 写文件头以获得正确的编码。
  • You can use the third parameter of fputcsv(...) to set the delimiter. 您可以使用fputcsv(...)的第三个参数来设置分隔符。

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

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