CSV to JSON with PHP?
Well there is the json_encode() function, which you should use rather than building up the JSON output yourself. And there is also a function str_getcsv() for parsing CSV:
$array = array_map("str_getcsv", explode("\n", $csv));print json_encode($array);
You must however adapt the $array if you want the JSON output to hold named fields.
I modified the answer in the question to use the first line of the CSV for the array keys. This has the advantage of not having to hard-code the keys in the function allowing it to work for any CSV with column headers and any number of columns.
Here is my modified version:
function csvToJson($csv) { $rows = explode("\n", trim($csv)); $data = array_slice($rows, 1); $keys = array_fill(0, count($data), $rows[0]); $json = array_map(function ($row, $key) { return array_combine(str_getcsv($key), str_getcsv($row)); }, $data, $keys); return json_encode($json);}
Some tips...
- If you have URL opening enabled for
fopen()
and wrappers, you can usefgetscsv()
. - You can build an array of the CSV, and then convert it with PHP's native
json_encode()
. - The correct mime type for JSON is
application/json
.