Convert CSV to JSON with header row as key - PHP andrey среда, 16 июля 2014 г. No Comment

When you get the data from CSV file, It will return return array of each row. If we want this array in JSON as header row as key and cell value as value, We can use PHP's array_combine function.

So, We can use this following function to achieve this task.

FUNCTION DEFENITION
function getJsonFromCsv($file,$delimiter) { 
if (($handle = fopen($file, 'r')) === false) {
die('Error opening file');
}

$headers = fgetcsv($handle, 4000, $delimiter);
$csv2json = array();

while ($row = fgetcsv($handle, 4000, $delimiter)) {
$csv2json[] = array_combine($headers, $row);
}

fclose($handle);
return json_encode($csv2json);
}
HOW IT WORKS

* Just read the first line separately and merge it into every row.
* The above function opens a file handle, reads the first line into $headers
* Then reads the remaining lines.
* It combines each line with the $headers.
* See how array_combine works.

PARAMETERS 

$file - File path
$delimiter - delimiter used in this CSV

FUNCTION USAGE
getJsonFromCsv($file_path, ',');
Recommended Article : Convert CSV to Two dimensional array (2D Array) - PHP

Have any doubt? Feel free to comment here!!!


When you get the data from CSV file, It will return return array of each row. If we want this array in JSON as header row as key and cell value as value, We can use PHP's array_combine function.

So, We can use this following function to achieve this task.

FUNCTION DEFENITION
function getJsonFromCsv($file,$delimiter) { 
if (($handle = fopen($file, 'r')) === false) {
die('Error opening file');
}

$headers = fgetcsv($handle, 4000, $delimiter);
$csv2json = array();

while ($row = fgetcsv($handle, 4000, $delimiter)) {
$csv2json[] = array_combine($headers, $row);
}

fclose($handle);
return json_encode($csv2json);
}
HOW IT WORKS

* Just read the first line separately and merge it into every row.
* The above function opens a file handle, reads the first line into $headers
* Then reads the remaining lines.
* It combines each line with the $headers.
* See how array_combine works.

PARAMETERS 

$file - File path
$delimiter - delimiter used in this CSV

FUNCTION USAGE
getJsonFromCsv($file_path, ',');
Recommended Article : Convert CSV to Two dimensional array (2D Array) - PHP

Have any doubt? Feel free to comment here!!!


by Jillur Rahman

Jillur Rahman is a Web designers. He enjoys to make blogger templates. He always try to make modern and 3D looking Templates. You can by his templates from Themeforest.

Follow him @ Twitter | Facebook | Google Plus

No Comment