Skip to content

Instantly share code, notes, and snippets.

@tomothumb
Forked from robflaherty/csv-to-json.php
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomothumb/c80b3d706838610219cf to your computer and use it in GitHub Desktop.
Save tomothumb/c80b3d706838610219cf to your computer and use it in GitHub Desktop.
class csvToJson{
var $feed = "";
function csvToJson($feed=""){
$this->feed = $feed;
}
function setFeed($feed){
$this->feed = $feed;
}
function process(){
// Arrays we'll use later
$keys = array();
$newArray = array();
// Do it
$data = $this->csvToArray($this->feed, ',');
// Set number of elements (minus 1 because we shift off the first row)
$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;
}
// Bring it all together
for ($j = 0; $j < $count; $j++) {
$d = array_combine($keys, $data[$j]);
$newArray[$j] = $d;
}
return json_encode($newArray);
}
function get(){
$json = $this->process();
return $json;
}
// Print it out as JSON
function show(){
$json = $this->get();
header('Content-type: application/json');
echo $json;
}
// Function to convert CSV into associative array
function csvToArray($file, $delimiter) {
if (($handle = fopen($file, 'r')) !== FALSE) {
$i = 0;
while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) {
for ($j = 0; $j < count($lineArray); $j++) {
$arr[$i][$j] = $lineArray[$j];
}
$i++;
}
fclose($handle);
}
return $arr;
}
}
CID LABEL COLORCODE
c0 white #FFF
c1 black #000
c2 red #F00
c3 blue #00F
c4 green #0F0
<?php
include_once("./csvtojson.php");
// Set your CSV feed
$feed = "./sample.csv";
// $feed = 'https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0Akse3y5kCOR8dEh6cWRYWDVlWmN0TEdfRkZ3dkkzdGc&single=true&gid=0&output=csv';
$f = new csvToJson($feed);
$f->show();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment