<?
header('Content-Type: application/json');
error_reporting(E_ERROR);
// 1ECowHw9wDaUt0AevWPutQnk3enmoB551st7VjXxzsl8
$DOC = $_GET['doc'];
if(!$DOC) exit(readfile('help.html'));
$GID = $_GET['gid'] ? $_GET['gid'] : 0;
$colNames = isset($_GET['colNames']);
$rowNames = isset($_GET['rowNames']);
$rowGroups = isset($_GET['rowGroups']);
if($rowGroups) $rowNames = true;
$tsv = file_get_contents("https://docs.google.com/spreadsheets/d/$DOC/pub?gid=$GID&single=true&output=tsv");
$lines = explode("\n",$tsv);
if($colNames)
$colNames = explode("\t", array_shift($lines) );
foreach($colNames as $k=>$v)
$colNames[$k] = trim($v," \r\n\t");
if($rowNames)
array_shift($colNames);
if(isset($_GET['colNamesLC']))
foreach($colNames as $k=>$v)
$colNames[$k] = strtolower($v);
if(isset($_GET['colNamesCC'])) // camel case
foreach($colNames as $k=>$v)
$colNames[$k] = lcfirst(str_replace(' ','',ucwords(strtolower($v))));
$out = array();
foreach($lines as $i=>$line){
$cols = explode("\t",$line);
if($rowNames)
$rowName = array_shift($cols);
$row = $rowName ? $rowName : $i;
foreach($cols as $j=>$column){
$col = $colNames[$j] ? $colNames[$j] : $j;
$tmp[$col] = trim($column," \r\n\t");
// $out[$row][$col] = trim($column," \r\n\t");
}
if($rowGroups)
$out[$row][] = $tmp;
else
$out[$row] = $tmp;
}
echo json_encode($out);
// print_r($lines);
// echo "<table>";
// foreach($lines as $line){
// $cols = explode("\t",$line);
// echo "<tr>";
// foreach($cols as $col){
// echo "<td>$col</td>";
// }
// echo "</tr>";
// }
// echo "</table>";
?>