PHP fputcsv()创建一个CSV导入outlook联系人


PHP fputcsv() to create a CSV to import into outlook contacts

我从数据库中获取值,并将它们插入csv文件中,以便下载并导入outlook。

我正在使用这个代码

// output headers so that the file is downloaded rather than displayed
$today = date("m.d.y");
header('Content-Type: text/csv;');
header('Content-Disposition: attachment; filename='.$today.'-allowners.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('firstname', 'lastname', 'email'));
// fetch the data
$rows = mysql_query('SELECT first_name, last_name, email FROM owners');
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);

我得到了奇怪的结果,首先列标题没有分隔符,其次不是数据库中的所有字段都用"分隔。输出如下:

firstname,lastname,email
" aaaaa"," bbbbb",0000
" aaaaa"," bbbbb"," 0000"
"aaaaa ",bbbbb,000@00000.com
 aaaaa,bbbbb,000.00.0@00000.com
" aaaaa"," bbbbb"," 000.00000@00000.com"
" aaaaa"," bbbbb"," 000000@000000.com"

当试图导入outlook时,它会给我一个错误,说明该文件无效或正在被另一个应用程序或进程使用。

---------------解决方案---------------

问题是用运行在linux上的php创建的文件在windows系统中打开时换行,这在某些软件中并不会造成麻烦,但由于是MS Outlook,所以它们似乎非常严格。我测试了用excel打开文件并保存为CSV覆盖现有文件,它工作起来没有问题。

解决方案可以在以下url中找到其他问题的答案。

http://stackoverflow.com/a/12723639/2633609

在您提供的示例输出中,您没有任何格式问题:

  • 不需要外壳(双引号)的字段没有双引号
  • 确实需要机柜的字段,请使用它们
  • 所有行中的所有字段都具有所需的分隔符(逗号)

给出的示例是一个有效的CSV输出,与此处的文档一致:php.net/manual/en/function.fputcsv.php

最令人怀疑的是,该文件没有用脚本末尾的fclose正确关闭。

由于不需要机柜,因此不添加这些机柜。所有被封闭的价值观都有相同的特点:它们有引导空间。

请记住,CSV是一种定义非常差的格式。几乎任何东西都可以是CSV。分隔符、外壳和转义符定义不正确。

至于你犯的错误。也许Excel想要分号分隔的文件?制表符分隔有时似乎也有效。这取决于您的语言/地区设置。