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?

2
  • possible duplicate of CSV to JSON with PHP? Commented Feb 9, 2014 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. Commented Feb 10, 2014 at 8:42

2 Answers 2

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.
 }
?>
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.