php newline not getting detected in csv

user1165952 picture user1165952 · Jun 22, 2012 · Viewed 7.3k times · Source

I have this common issue of 'new line' in php-csv which is making me crazy!!! I checked so many forums and tried different workarounds, but it doesn't seem to fix the problem. I'm reading from a CSV file which has 1 header and 2 data records. I skip the header using fgets() and reading the data records using $data=fgetcsv(). Now the problem is both the data records are read into single array. I tried the following options, but all in vain:

  1. Runtime - ini_set("auto_detect_line_endings", true);
  2. Turned auto_detect_line_endings to 'ON' in php.ini.
  3. tried fwrite($handle, implode($delimiter,$fieldsarray).PHP_EOL);

I'm working on MAMP in local, LAMP in dev region. The CSVs are saved on local machine, copied to /tmp/ folder and read from there. How can I check if there are necessary newlines in the files? When i check the file from tmp, I do see the records in new lines.

Answer

user1165952 picture user1165952 · Jun 25, 2012

The following solution worked!!

$file_contents = file_get_contents($temp);
$file_cont_new = str_replace("\n","\r",$file_contents);
file_put_contents($temp,$file_cont_new);