fputcsv和换行代码 [英] fputcsv and newline codes

查看:58
本文介绍了fputcsv和换行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PHP中使用fputcsv输出数据库查询的逗号分隔文件.在Ubuntu中的gedit中打开文件时,它看起来是正确的-每个记录都有一个换行符(没有可见的换行符,但是您可以告诉每个记录是分开的,并且在OpenOffice电子表格中打开它可以让我正确地查看文件.)

I'm using fputcsv in PHP to output a comma-delimited file of a database query. When opening the file in gedit in Ubuntu, it looks correct - each record has a line break (no visible line break characters, but you can tell each record is separated,and opening it in OpenOffice spreadsheet allows me to view the file correctly.)

但是,我们将这些文件发送到Windows上的客户端上,在他们的系统上,文件排成一行,很长.在Excel中打开它,它根本无法识别多行.

However, we're sending these files on to a client on Windows, and on their systems, the file comes in as one big, long line. Opening it in Excel, it doesn't recognize multiple lines at all.

我在这里阅读了几个非常相似的问题,包括这个问题,其中包括链接到真正有用的 Great Newline Schism 解释.

I've read several questions on here that are pretty similar, including this one, which includes a link to the really informative Great Newline Schism explanation.

不幸的是,我们不能仅仅告诉客户在更智能"的编辑器中打开文件.他们需要能够在Excel中打开它们.是否有任何编程方式来确保添加正确的换行符,以便可以在任何OS上的电子表格程序中打开文件?

Unfortunately, we can't just tell our clients to open the files in a "smarter" editor. They need to be able to open them in Excel. Is there any programmatic way to ensure that the correct newline characters are added so the file can be opened in a spreadsheet program on any OS?

我已经在使用自定义函数来强制所有值都用引号引起来,因为fputcsv是有选择的.我已经尝试做过这样的事情:

I'm already using a custom function to force quotes around all values, since fputcsv is selective about it. I've tried doing something like this:

function my_fputcsv($handle, $fieldsarray, $delimiter = "~", $enclosure ='"'){

        $glue = $enclosure . $delimiter . $enclosure;

    return fwrite($handle, $enclosure . implode($glue,$fieldsarray) . $enclosure."\r\n");

}

但是在Windows文本编辑器中打开文件时,它仍然显示为一行.

But when the file is opened in a Windows text editor, it still shows up as a single long line.

推荐答案

我最终在Experts-exchange上得到了答案.这是有效的方法:

I did eventually get an answer over at experts-exchange; here's what worked:

function my_fputcsv($handle, $fieldsarray, $delimiter = "~", $enclosure ='"'){
   $glue = $enclosure . $delimiter . $enclosure;
   return fwrite($handle, $enclosure . implode($glue,$fieldsarray) . $enclosure.PHP_EOL);
}

用于代替标准fputcsv.

to be used in place of standard fputcsv.

这篇关于fputcsv和换行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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