3

I would like to convert a CSV to Json, use the header row as a key, and each line as object. How do I go about doing this?

----------------------------------CSV---------------------------------

 InvKey,DocNum,CardCode
 11704,1611704,BENV1072
 11703,1611703,BENV1073

---------------------------------PHP-----------------------------------

  if (($handle = fopen('upload/BEN-new.csv'. '', "r")) !== FALSE) {
       while (($row_array = fgetcsv($handle, 1024, ","))) {
            while ($val != '') {
                foreach ($row_array as $key => $val) {
                        $row_array[] = $val;
                        }
                }
            $complete[] = $row_array;   
            }
            fclose($handle);
        }
        echo json_encode($complete);
MG1
  • 1,655
  • 9
  • 33
  • 46

4 Answers4

19

Just read the first line separately and merge it into every row:

if (($handle = fopen('upload/BEN-new.csv', 'r')) === false) {
    die('Error opening file');
}

$headers = fgetcsv($handle, 1024, ',');
$complete = array();

while ($row = fgetcsv($handle, 1024, ',')) {
    $complete[] = array_combine($headers, $row);
}

fclose($handle);

echo json_encode($complete);
deceze
  • 510,633
  • 85
  • 743
  • 889
  • 4
    What don't you understand about it? It opens a file handle, *reads the first line* into `$headers`, then reads the remaining lines. It combines each line with the `$headers`. See [array_combine](http://php.net/array_combine). – deceze May 23 '12 at 03:14
1

I find myself converting csv strings to arrays or objects every few months.

I created a class because I'm lazy and dont like copy/pasting code.

This class will convert a csv string to custom class objects:

Convert csv string to arrays or objects in PHP

Amado Martinez
  • 429
  • 2
  • 8
1
$feed="https://gist.githubusercontent.com/devfaysal/9143ca22afcbf252d521f5bf2bdc6194/raw/ec46f6c2017325345e7df2483d8829231049bce8/data.csv";
//Read the csv and return as array
$data = array_map('str_getcsv', file($feed));
//Get the first raw as the key
$keys = array_shift($data);  
//Add label to each value
$newArray = array_map(function($values) use ($keys){
    return array_combine($keys, $values);
}, $data);
// Print it out as JSON
header('Content-Type: application/json');
echo json_encode($newArray);

Main gist: https://gist.github.com/devfaysal/9143ca22afcbf252d521f5bf2bdc6194

devfaysal
  • 167
  • 2
  • 9
0

For those who'd like things spelled out a little more + some room to further parse any row / column without additional loops:

function csv_to_json_byheader($filename){
    $json = array();
    if (($handle = fopen($filename, "r")) !== FALSE) {
        $rownum = 0;
        $header = array();
        while (($row = fgetcsv($handle, 1024, ",")) !== FALSE) {
            if ($rownum === 0) {
                for($i=0; $i < count($row); $i++){
// maybe you want to strip special characters or merge duplicate columns here?
                    $header[$i] = trim($row[$i]);
                }
            } else {
                if (count($row) === count($header)) {
                    $rowJson = array();                     
                    foreach($header as $i=>$head) {
                // maybe handle special row/cell parsing here, per column header
                        $rowJson[$head] = $row[$i];                     
                    }
                    array_push($json, $rowJson);
                }
            }
            $rownum++;
        }
        fclose($handle);
    }
    return $json;
}
E.A.T
  • 848
  • 11
  • 24