Converting CSV to JSON with PHP

JSON is a little bit more verbose then csv (comma seperated values), but widely used nowadays on the net, because it format is somewhat like a literal Javascript object. Now Javascript and PHP have native JSON support it is a very good and handy format to exchange data, much less verbose then XML and easier to create and parse on the client.

How easy?

In PHP:

 json_encode ($array);
 json_decode($json);

In Javascript:


JSON.stringify(myObject)
JSON.parse(myJson)


But csv is also still widely used:
  • myslq dump
  • spreadsheet
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

explode(",", $line);

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:

print json_encode($array,JSON_PRETTY_PRINT);

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.

Comments are closed.

Categories
Archives
Links