3

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?

2
  • 3
    Difference is the line ending characters.... 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.
    – Mark Baker
    May 13, 2013 at 13:52
  • Look into auto_detect_line_endings May 13, 2013 at 13:54

3 Answers 3

14

The answer is in the PHP doc comments:

http://be2.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);
0

Mac and Windows use different EOL characters. That gets confusing on the best of days. Here is a good explanation of how they work on different platforms: http://peterbenjamin.com/seminars/crossplatform/texteol.html

0

The return characters in Windows are \r in Mac I believe its \r\n.

1
  • 3
    It's \r\n on windows, \n on unix and is (was?) \r on mac May 13, 2013 at 13:55

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.