在PHP中处理CSV文件,能够满足MS和UNIX换行符的要求 [英] Processing CSV File in PHP that able to cater MS and UNIX Line Break

查看:107
本文介绍了在PHP中处理CSV文件,能够满足MS和UNIX换行符的要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个处理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行组成,并且所有数据都填充到$ he​​ader。

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.NET :Windows提供了一个文本模式转换标记('t'),该标记将透明地显示在处理文件时将\n转换为\r\n。相反,您也可以使用'b'强制使用二进制模式,该模式不会转换您的数据。要使用这些标志,请将'b'或't'指定为mode参数的最后一个字符。

From PHP.NET : Windows offers a text-mode translation flag ('t') which will transparently translate \n to \r\n when working with the file. In contrast, you can also use 'b' to force binary mode, which will not translate your data. To use these flags, specify either 'b' or 't' as the last character of the mode parameter.

有什么办法吗?最好只通过更改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);
        }


推荐答案

auto_detect_line_endings

ini_set('auto_detect_line_endings',true);

这篇关于在PHP中处理CSV文件,能够满足MS和UNIX换行符的要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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