Processing CSV File in PHP that able to cater MS and UNIX Line Break

▼魔方 西西 提交于 2019-12-11 21:14:03

问题


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.

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.

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 .

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.

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);


来源:https://stackoverflow.com/questions/19720046/processing-csv-file-in-php-that-able-to-cater-ms-and-unix-line-break

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!