Wednesday, 16 July 2014

Convert CSV to JSON with header row as key - PHP 1

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!!!


1 comment:

  1. Hi, the function is not parsing cells with space e.g. "Firstname Lastname". It is returning "" in place of the cell values

    ReplyDelete