fgetcsv in PHP fails with Mac-created files

08 01 2010
Today I had a problem importing a CSV file in PHP. It seems that apache doesn't properly regognize the line endings from the csv file.

When CSV the file has been created on a Mac, you will get problems when using fgetcsv to parse CSV files under PHP: The line endings are incorrectly interpreted.

Try the following code:



'auto_detect_line_endings' enables PHP to interoperate with Macintosh systems and look after which line-ending conventions is used.

The common line endings are:
\n (UNIX/Linux)
\n\r (Windows)
\r (Mac)

Here is an wikipedia article about the historical reason behind different line ending at different platforms: Newline History


Bookmark fgetcsv in PHP fails with Mac-created files  at del.icio.us Digg fgetcsv in PHP fails with Mac-created files Mixx fgetcsv in PHP fails with Mac-created files Bloglines fgetcsv in PHP fails with Mac-created files Technorati fgetcsv in PHP fails with Mac-created files Bookmark fgetcsv in PHP fails with Mac-created files  at Furl.net Bookmark fgetcsv in PHP fails with Mac-created files  at blogmarks Bookmark fgetcsv in PHP fails with Mac-created files  at Ma.gnolia.com wong it! Stumble It!

Trackbacks


No Trackbacks

Comments

Display comments as (Linear | Threaded)
14 01 2010
#1 manuw (Reply)

manuwfunction breakdancer($line){
return str_replace(array('\r\n','\0','\v','\t','\r',chr(13),chr(10),chr(21)),'\n', trim($line));
}
30 01 2010
#1.1 PHP Gangsta (Reply)

PHP Gangsta@manuw: I don't understand your function.
chr(13)
30 01 2010
#2 PHP Gangsta (Reply)

PHP GangstaOh, my last comment was stripped (bug in blog software, I used a "less than" character in my comment)

@manuw: I don't understand your function.
chr(13) -- Carriage Return: \r is already in the list
chr(10) -- Line Feed: you replace \n with \n ?
chr(21) -- This is a NAK character, why is it in the list?

What is \v, I've never seen this?!

Add Comment


Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.
Standard emoticons like :-) and ;-) are converted to images.
E-Mail addresses will not be displayed and will only be used for E-Mail notifications

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.
CAPTCHA