0

It's strange PHP Reading my Excel generated CSV file into a single line. Code is:

if ($file) {
                while (($line = fgets($file)) !== false) {
                    print '<div>'.$line.'</div>'."<br/>";
                }

            } else {
                // error opening the file.
            }

            fclose($file);

CSV

Name, City
Jon,Paris
Doe,Madrid
1

2 Answers 2

2

Add this code before reading the file.

ini_set("auto_detect_line_endings", true);

When turned on, PHP will examine the data read by fgets() and file() to see if it is using Unix, MS-Dos or Macintosh line-ending conventions.

This enables PHP to interoperate with Macintosh systems, but defaults to Off, as there is a very small performance penalty when detecting the EOL conventions for the first line, and also because people using carriage-returns as item separators under Unix systems would experience non-backwards-compatible behaviour.

Sign up to request clarification or add additional context in comments.

Comments

1

Most likely, PHP is not correctly detecting the line endings in your file. The fgets documentation points this out.

You will probably want to write code like this:

$oldLineEndings = ini_set('auto_detect_line_endings', true);

//your while loop here

ini_set('auto_detect_line_endings', $oldLineEndings);

If you need to actually parse the csv, you may also want to look at fgetcsv.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.