-
-
Save shoxty/7680559 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
<?php | |
class CsvToJson { | |
private $feed = ''; | |
private $data = array(); | |
public function __construct($feed) { | |
$this->feed = $feed; | |
} | |
public function get_data() { | |
$this->data = $this->csv_to_array(); | |
return $this->clean_up_array_format(); | |
} | |
public function render() { | |
$data = $this->get_data(); | |
header('Content-type: application/json'); | |
echo json_encode($data); | |
} | |
private function csv_to_array() { | |
$file = $this->feed; | |
$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; | |
} | |
private function clean_up_array_format() { | |
$keys = array(); | |
$newArray = array(); | |
$count = count($this->data) - 1; | |
$labels = array_shift($this->data); | |
foreach ($labels as $label) { | |
$keys[] = $label; | |
} | |
$keys[] = 'id'; | |
for ($i = 0; $i < $count; $i++) { | |
$this->data[$i][] = $i; | |
} | |
for ($j = 0; $j < $count; $j++) { | |
$d = array_combine($keys, $this->data[$j]); | |
$newArray[$j] = $d; | |
} | |
return $newArray; | |
} | |
} | |
# create a new instance of the class and pass in your public doc url, output must be csv | |
$Spreadsheet = new CsvToJson('https://docs.google.com/spreadsheet/pub?key=0Ah_ZDt4fQfvYdFRUZTZpVkc5M1VJcGhvLVVNOVRvc2c&single=true&gid=2&output=csv'); | |
# then call render(). this sets the content type to application/json and outputs the json | |
$Spreadsheet->render(); | |
# however, if you want to play with the data, you can call the get_data() method instead of render() and itll return the data as an array | |
# $data = $Spreadsheet->get_data(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment