Kieron606
Kieron606

Reputation: 613

PHP str_getcsv to JSON

I am trying to use str_getcsv to convert from CSV to JSON.

I'm nearly there the problem I am having is with formatting the JSON, I need the format to be like this to use in DataTables -

{"data":[["Debra Brown"]

But it is

{"data":["[[\"Debra Brown\"]

My code

$csv = file_get_contents($targetPath);
$csvArray = array_map("str_getcsv", file($targetPath));
$csvToJson = json_encode($csvArray);

print_r($csv);

$csvJsonArray = array();

$csvJsonArray['data'][] = $csvToJson;
echo json_encode($csvJsonArray);   

My CSV - CSV

Upvotes: 1

Views: 309

Answers (1)

fusion3k
fusion3k

Reputation: 11689

You re-encode already encoded string.

Add data key before encoding data:

$csvArray = array_map( 'str_getcsv', file( $targetPath ) );
$csvArray = array( 'data' => $csvArray );
$csvToJson = json_encode( $csvArray );

Result:

{"data":[["Debra Brown"],["Jacqueline Garza"], (...) ]}

Upvotes: 3

Related Questions