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

4 Answers 4

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

1 Comment

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

Comments

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

Comments

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

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.