Last active
January 3, 2016 17:29
-
-
Save jamesmm77/8495905 to your computer and use it in GitHub Desktop.
A function that pulls a published public Google Drive Spreadsheet (in csv format) and converts the csv to an html table.
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
/** | |
* Show Google Drive CSV as HTML Table - show_gdoc_csv_html_table() | |
* Parameters: | |
* (url) - required string of url to published to the web google drive spreadsheet (not just shared) in csv format (&output=csv) | |
* (table_id) - optional string used for the table's id, appended to data-table-, defaults to 1 | |
* (table_headers) - optional boolean to show first row with Table Headers (<th>), defaults to FALSE | |
*/ | |
function show_gdoc_csv_html_table($url, $table_id='1', $table_headers=FALSE) { | |
// generate cache filename from url | |
$url_filename = 'cache/' . md5($url) . '.cache'; | |
// if file does not exists OR if older than 15 mins, | |
// get current and save to cache filename | |
if ( !file_exists($url_filename) OR time() - filemtime($url_filename) >= 15*60 ) { | |
file_put_contents($url_filename,file_get_contents($url)); | |
//echo 'made new cache'; | |
} | |
$html='<table id="data-table-' . $table_id . '" class="data-table data-table-' . $table_id . '" border="0" cellpadding="0" cellspacing="0">'; | |
$row=1; | |
$f=fopen($url_filename, "r"); | |
while ( ($line = fgetcsv($f) ) !== false ) { | |
$html.='<tr class="row-'.($row).' row-'.($row%2==0?'even':'odd').'">'; | |
$col=1; | |
foreach ( $line as $cell ) { | |
if ($cell=='') $cell=' '; | |
if ($row==1 && $table_headers===TRUE) { | |
$html.='<th class="col-'.($col).'">'.htmlspecialchars($cell).'</th>'; | |
} else { | |
$html.='<td class="col-'.($col).'">'.htmlspecialchars($cell).'</td>'; | |
} | |
++$col; | |
} | |
$html.='</tr>'; | |
++$row; | |
} | |
fclose($f); | |
$html.='</table>'; | |
return $html; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment