1

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

1 Answer 1

3

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"], (...) ]}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.