-
-
Save tomothumb/c80b3d706838610219cf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CID | LABEL | COLORCODE | |
---|---|---|---|
c0 | white | #FFF | |
c1 | black | #000 | |
c2 | red | #F00 | |
c3 | blue | #00F | |
c4 | green | #0F0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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