Skip to content

Instantly share code, notes, and snippets.

@rileypaulsen
Last active December 27, 2015 19:18
Show Gist options
  • Save rileypaulsen/7375700 to your computer and use it in GitHub Desktop.
Save rileypaulsen/7375700 to your computer and use it in GitHub Desktop.
Outputs a Google Spreadsheet's CSV feed as valid JSON
<?php
header('Content-type: application/json');
// Based on http://www.ravelrumba.com/blog/json-google-spreadsheets/
//#########################################################
$key = '';
$gid = '0'; //the sheet of the spreadsheet
//#########################################################
// 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;
}
// Set up the CSV feed
$feed = "https://docs.google.com/spreadsheet/pub?key=$key&single=true&gid=$gid&output=csv";
// Get the data
$data = csvToArray($feed, ',');
// Set number of elements (minus 1 because we shift off the first row)
$numRows = count($data) - 1;
//Use first row for names
$keys = array();
$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 < $numRows; $i++) {
$data[$i][] = $i;
}
// Merge the arrays for each row to ensure associative arrays that come back as objects in JSON
$jsonData = array();
for ($j = 0; $j < $numRows; $j++) {
$jsonData[$j] = array_combine($keys, $data[$j]);
}
// Print it out as JSON
die(json_encode($jsonData));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment