Monday, September 11, 2006

How to Read and Write CSV in PHP 5, with no mess.

File_CSV is evil.

So are homebrew solutions.

PHP 5.1+ has fgetcsv() and fputcsv().

Use them, or I'll whap you with a stick.

4 comments:

Yoz said...

Ah, thank you. I was looking for decent CSV-parsing code in PHP not three days ago and wondering why File_CSV was so poor.

Why do you say 5.1, though? Docs seem to indicate it's 4+.

Also, why is that doc page full of people reimplementing an existing function in a worse fashion?

CloCkWeRX said...

(PHP 5 >= 5.1.0RC1) for fputcsv.

It's one of life's great mysteries: people, including some I work with, reinventing the wheel over and over.

Anonymous said...

but what about , and ". fputcsv doesn't escape those, how do you deal with these? I'm using OpenOffice's Calc. I don't know if this might be the issue, but when I have a comma in the string, the value gets split in two different cells.

CloCkWeRX said...

If it's a problem, make a simple test case and file a bug.