- PHP -
json_encode ($array); json_decode($json);
But csv is also still widely used:
- myslq dump
To concert CSV to JSON in PHP is actually quite simple:
$file="mysqlTable.csv"; $csv= file_get_contents($file); $array = array_map("str_getcsv", explode("\n", $csv)); print json_encode($array);
The first two lines are simple, and do not need any explaining.
Convert CSV into an array
The third line, converts the csv file into a multidimensional array
$array = array_map("str_getcsv", explode("\n", $csv));
Explode the csv string on `line ends` into an array of lines, and convert the lines themselves with the safe native function `str_getcsv` to an array. Although it is tempting to parse a line of csv with
always use the native functions for csv like, str_getcsv.
Convert an array into JSON
Once you have the $array, simply convert it to JSON:
JSON_PRETTY_PRINT is optional and will print the JSON with whitespace.
Use it for debugging, don’t use it in production, it will add extra whitespace and thus size to your output.
Create JSON/Ajax server response
header('Content-Type: application/json'); print json_encode($array);
Turns your server into Ajax serving JSON.