1

I have csv file like this:

data,IF,VVS1,VVS2
D,23,17,15
E,17,15,14

What i need is to convert this CSV into JSON but to look like this:

{"D" : {"IF":"23", "VVS1":"17", "VVS2":"15"},"E" : {"IF":"17", "VVS1":"15", "VVS2":"14"}}

Any help?

iva
  • 173
  • 1
  • 11
  • possible duplicate of [CSV to JSON with PHP?](http://stackoverflow.com/questions/4811844/csv-to-json-with-php) – hichris123 Feb 09 '14 at 18:15
  • those answers were setting each row as an object, but problem was that I needed first column to be "key" of the nested object. – iva Feb 10 '14 at 08:42

2 Answers2

2

Maybe help you, but I recommend add error handling.

<?php

$file = fopen('test.csv', 'r');

$header = fgetcsv($file);
array_shift($header);

$data = array();

while ($row = fgetcsv($file))
{
  $key = array_shift($row);

  $data[$key] = array_combine($header, $row);
}

echo json_encode($data);

fclose($file);
Jiří Chmiel
  • 876
  • 6
  • 20
2

/* Lets suppose, the csv file is, mydata.scv */

<?php
 $mydata = array();

 if($file = fopen("mydata.csv","r")){
   $csvheaders = fgetcsv($file);
   while(($row = fgetcsv($file)) !== FALSE){
     $arr = array();
     for($i=1; $i<count($csvheaders); $i++){
      $arr[$csvheaders[$i]] = $row[$i];
     } 
     $mydata[$row[0]] = $arr;
    }
  fclose($file);
  // encode $mydata array into json to get result in the required format
  $mydatainformat = json_encode($mydata);
  echo $mydatainformat; // This is your output.
 }
?>
Suraj Kumar
  • 564
  • 1
  • 3
  • 11