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.

6 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.

Anonymous said...

Fantastic tutorial man. The link to the php manuel is just so helpful. Glad google brought me on this useless page for nothing

Daniel O'Connor said...

Hi. You must be new here. Back when this was written, php 5.1 was new. It is no longer. If you are still incapable of writing csv aftrr rtfm, you may be developmentally challanged.