0

The below php takes my csv file and outputs to JSON file.

<?php

    echo "<h2>Uploading....</h2>";

    $fh = fopen("assets/files/locationsCSV.csv", "r");

    $csvData = array();

    while (($row = fgetcsv($fh, 0, ",")) !== FALSE) {
        $csvData[] = $row;
    }
    // echo json_encode($csvData);
    file_put_contents("assets/files/locationsCSV.json",json_encode($csvData))      

?> 

the JSON in my json file outputs like this, below: Current Output:

["Zipcode","City","Primary State","SS","County"], # only prints once
["24553","","Virginia","49050","Appomattox"], # then just this 
["24553","","Virginia","49140","Buckingham"], # etc

How could I get it to output like this/reformatted with zipcode column as object header?

Desired JSON output:

{ 
 ZipCode: 24553, { 
 City: , 
 Primary State: Virginia, 
 SS: 49050,
 County: Appomattox
}
1
  • 1
    Is the trailing "{" in ZipCode: 24553, { a typo? Because it's not valid JSON :) Commented Apr 23, 2019 at 23:41

1 Answer 1

1

You need to read the first row of your CSV file into a keys array, and the combine those keys with each row of data in your loop:

$csvData = array();
$keys = fgetcsv($fh, 0, ",");
while (($row = fgetcsv($fh, 0, ",")) !== FALSE) {
    $csvData[] = array_combine($keys, $row);
}
Sign up to request clarification or add additional context in comments.

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.