问题描述
我有一个处理CSV文件作为输入的模块。
I have a module that process a CSV File as Input. It works fine in my Ubuntu machine, until someone in my team start to use Microsoft Excel to create the csv.
结果是,新输入的CSV具有^ M (\r\n)字符,因此,我的代码假定CSV仅由1行组成,并且所有数据都填充到$ header。
As the result, the new input CSV is having ^M ( \r\n ) characters on it, and because of that, my code assumes that the CSV is consist of 1 line only, and all the data is populated to $header.
我已将读取模式更改为 rt,因为php.net建议以t模式打开文本,但是问题仍然存在。似乎rt仅适用于Windows将\n转换为\rn
。
I have changed the read mode to "rt" since the php.net advises to open text in t mode, but the issue is still exist. It seems that rt is only works for Windows to convert \n to \rn.
有什么办法吗?最好只通过更改PHP代码来接受两种换行符(Microsoft和UNIX)?我知道有 dos2unix (ubuntu中的fromdos)命令,但是最新的Ubuntu默认情况下没有此命令,我想避免安装其他实用程序。
Is there any way to accept both kind of newline ( Microsoft and UNIX ) preferably by changing the PHP code only? I understand there is dos2unix (fromdos in ubuntu) command but latest Ubuntu does not have this by default and I want to refrain from installing other utility.
下面是我当前的源代码:
Below is my current source code :
$row = 1;
if (($handle = fopen($file, "r")) !== FALSE)
{
while (($data = fgetcsv($handle)) !== FALSE)
{
$num = count($data);
if($row == 1)
{
$header = $data;
}else
{
$rows[$row-1] = $data;
}
$row++;
}
fclose($handle);
}
推荐答案
ini_set('auto_detect_line_endings',true);
这篇关于在PHP中处理CSV文件,能够满足MS和UNIX换行符的要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!