CSV to JSON conversion using PHP

CSV to json conversion.

         $feed = $url; // path to the csv file
            $keys = array();
            $newArray = array();
            $data = csvToArray($feed, ',');
            $count = count($data) - 1;
            //Use first row for names 
            $labels = array_shift($data);
            foreach ($labels as $label) {
                $keys[] = $label;
            }
           // Add Ids, just in case we want them later
            $keys[] = 'id';
            for ($i = 0; $i < $count; $i++) {
                $data[$i][] = $i;
            }
            for ($j = 0; $j < $count; $j++) {
                $d = array_combine($keys, $data[$j]);
                $newArray[$j] = $d;
            }
           $json_data = json_encode($newArray);
           header('Content-disposition: attachment; filename='.$file_name.'.json');
           header('Content-type: application/json');
          echo $json_data;

Leave a Comment.