Federico Moretti
Federico Moretti

Reputation: 89

PHP str_getcsv doesn't separate elements in the index 1 and 2

I'm importing a CSV and creating a 2D array with it. The problem is that in the indexes 1 and 2 the function doesn't recognize the separator "," so every array is ok but the ones in the second and third position.

I tried with multiple files, multiple software (LibreOffice, Google Spreadsheet) and it has always the same problem.

This is the code:

$dbLocation = 'upload/db.csv';

$paramStrGetCsv = array(",", '"', "\\");
$db = array_map('str_getcsv', file($dbLocation), $paramStrGetCsv);

print "<pre>";
print_r($db);
print "</pre>";

This is the array $db:

Array
(
    [0] => Array
        (
            [0] => email
            [1] => name
            [2] => surname
            [3] => birthdate
        )

    [1] => Array
        (
            [0] => [email protected],red,qwer,1990-06-01
        )

    [2] => Array
        (
            [0] => [email protected],blue,poiu,1990-01-01
        )

    [3] => Array
        (
            [0] => [email protected]
            [1] => green
            [2] => yuiop
            [3] => 1980-01-01
        )

    [4] => Array
        (
            [0] => [email protected]
            [1] => purple
            [2] => zxcvbn
            [3] => 1975-01-01
        )

    [5] => Array
        (
            [0] => [email protected]
            [1] => yellow
            [2] => vbnm
            [3] => 1970-01-01
        )
)

This is the csv file:

email,name,surname,birthdate
[email protected],red,qwer,1990-06-01
[email protected],blue,poiu,1990-01-01
[email protected],green,yuiop,1980-01-01
[email protected],purple,zxcvbn,1975-01-01
[email protected],yellow,vbnm,1970-01-01

Thank you, Federico.

Upvotes: 0

Views: 99

Answers (1)

apokryfos
apokryfos

Reputation: 40663

So here's your problem:

$db = array_map('str_getcsv', file($dbLocation), $paramStrGetCsv);

First entry will run function str_getcsv("email,name,surname,birthdate", ",")

Second will run str_getcsv([email protected],red,qwer,1990-06-01, "\"")

and generally array map maps mutliple arrays using a single function which accepts multiple arguments, so it will try to use both the file and the $paramStrGetCsv to do the mapping. Instead do this:

$db = array_map(function ($ln) { return str_getcsv($ln,",", '"', "\\"); }, file($dbLocation));

Upvotes: 1

Related Questions