Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between windows csv and mac csv?

Tags:

php

csv

I am trying to parse a csv file using this code

if (($handle = fopen($csvFilePath, "r")) !== FALSE) {
        $c=0;
        $string="";
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        if($c>0)
        {
        if(($data[$email]!="") and ($data[$firstname]!="") and ($data[$lastname]!=""))
        {
        $string.='(1,';         
            $string.="'".$data[$email]."',";
            $string.="'".$data[$firstname]."',";
            $string.="'".$data[$lastname]."',";
            $string.="'".Yii::app()->params['clientimporttext']."'";

       $string.='),';
       }
        }
        $c++;
    }
fclose($handle);

}

It is working fine with windows csv.
but when i create a csv from mac and parse that it is not working.( it cant identify end of line),

also when i open the same windows csv with mac and parse using the same code it is not working.
but when i save it as windows csv. it again works.
so actually wat is the difference between mac csv and windows csv?
Is the delimiter different for these two?
How should i change the code to make it work with both?

like image 263
Mahesh Eu Avatar asked Feb 14 '26 08:02

Mahesh Eu


1 Answers

The answer is in the PHP doc comments:

https://www.php.net/manual/en/function.fgetcsv.php

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

The problem is in the difference between line endings on Windows and unix-like machines (as your mac is): windows ='\r\n' and unix = '\n'

The solution: add this line before opening the file:

ini_set('auto_detect_line_endings',TRUE);
like image 79
Borniet Avatar answered Feb 16 '26 23:02

Borniet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!