tags:

views:

51

answers:

2

I am trying to parse a .csv file into a mysql database, and it's not fun.

Some rows look like this:

"Value", Value, "Value3", ,"Value,Value"

And some look like this:

Value, Value, , Value, , Value

This preg_split worked well except for fields that were empty:

foreach ($row as $item) {
     $item = preg_split( "/[,]*\\\"([^\\\"]+)\\\"[,]*|[,]+/", $item, 0, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
}

When I removed "PREG_SPLIT_NO_EMPTY", I got an extra, empty value added at the end of $item. Is there a regex expression that would work for this?

A: 

For example:

list($name, $email, $phone) = explode(",", $user);

I guess explode would work better in this case.

Prix
+7  A: 

Why not use LOAD DATA INFILE

Alternatively, use PHP's built in fgetcsv() or str_getcsv() functions rather than messing about with regular expressions trying to reinvent the wheel

Mark Baker
very insteresting functions i wasnt aware of, cookie for you.
Prix
+1. Don't write your own CSV parser. It's harder than you think. You'll get it wrong.
bobince