CSV for Json with header as key

I would like to convert CSV to Json, use the title bar as a key and each line as an object. How should I do it?

---------------------------------- 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);
+3
source share
3 answers

Just read the first line separately and combine it into each line:

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);
+13
source

I find that I convert csv strings to arrays or objects every few months.

I created a class because I'm lazy and don't like copy / paste code.

This class converts the csv string to custom class objects:

Convert csv string to arrays or objects in PHP

+1

, , - + / :

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;
}
0

All Articles