3

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?

minimalpop
  • 6,997
  • 13
  • 68
  • 80
  • I would use `file_get_contents` to load the CSV, then `explode(",", $csvfile)` then manipulate the array until you get it to look like you want to and finally `json_encode` it. – SSH This Jun 13 '13 at 20:36
  • Loop over list, append to groups `$output["name"][] = $row[0];`. Show your current attempt if you need further advise. – mario Jun 13 '13 at 20:39

3 Answers3

5

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;
The Surrican
  • 29,118
  • 24
  • 122
  • 168
0

There are a few helpful php functions that will do what you need.

Open fopen and parse with fgetcsv.

Once you have your array use *json_encode* to get it into JSON format.

Something like this might work (not tested):

$results = array();
$headers = array();

//some parts ripped from http://www.php.net/manual/en/function.fgetcsv.php
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    $line = 0;
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            for ($x=0; $x < count($data); $c++) {
                if ($line == 0) {
                    $headers[] = $data[$x];
                }
                $results[$x][] = $data[$x];
            }
    }
    fclose($handle);
}

$output = array();

$x = 0;
foreach($headers as $header) {
    $output[$header] = $results[$x++];
}

json_encode($output);
crowebird
  • 2,488
  • 1
  • 17
  • 20
0

Compact solution:

<?php
$fp = fopen('file.csv', 'r');
$array = array_fill_keys(array_map('strtolower',fgetcsv($fp)), array());
while ($row = fgetcsv($fp)) {
    foreach ($array as &$a) {
        $a[] = array_shift($row);
    }
}
$json = json_encode($array);
dev-null-dweller
  • 29,274
  • 3
  • 65
  • 85