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?

1

1 Answer 1

8

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

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

1 Comment

+1. Don't write your own CSV parser. It's harder than you think. You'll get it wrong.

Your Answer

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