• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

在PHP处理CSV文件,能够满足MS和UNIX换行符的要求

用户头像
it1352
帮助1

问题说明

我有一个处理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.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);
        }

正确答案

#1

auto_detect_line_endings

ini_set('auto_detect_line_endings',true);

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfhacc
系列文章
更多 icon
同类精品
更多 icon
继续加载