Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP convert CSV to specific JSON format

I have a CSV file that looks like:

Name, Id, Address, Place,
John, 12, "12 mark street", "New York",
Jane, 11, "11 bark street", "New York"...

I have about 500 coloumns. I would like to convert this to JSON, but I want the output to look like:

{
    "name": [
        "John",
        "Jane"
    ],
    "Id": [
        12,
        11
    ],
    "Address": [
        "12 mark street",
        "12 bark street"
    ],
    "Place": [
        "New York",
        "New York"
    ]
}

Using PHP, how can I iterate through the CSV file so that I can make each column in the first row an array that holds the values in the same column on all the other rows?

like image 220
minimalpop Avatar asked Dec 09 '25 23:12

minimalpop


1 Answers

this would be a generic method which is valid for any amoutn of named colums. if they are static, it will be shorter to address them directly

<?
$result = array();
if (($handle = fopen("file.csv", "r")) !== FALSE) {
    $column_headers = fgetcsv($handle); // read the row.
    foreach($column_headers as $header) {
            $result[$header] = array();
    }

    while (($data = fgetcsv($handle)) !== FALSE) {
        $i = 0;
        foreach($result as &$column) {

                $column[] = $data[$i++];
        }

    }
    fclose($handle);
}
$json = json_encode($result);
echo $json;
like image 168
The Surrican Avatar answered Dec 12 '25 13:12

The Surrican



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!