问题
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