Created
May 28, 2015 16:37
-
-
Save jzpeepz/54a272e022f75678142b to your computer and use it in GitHub Desktop.
Easy way to pull items from a public Google Doc
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 | |
$doc = new GoogleDoc('1eJZsnDQ991VjHRqt9e9VUiDvp8s6WywSTAlqULPpx4g'); | |
$distributors = $doc->getEntries(); | |
?> | |
<table class="table distributors tablesorter"> | |
<thead> | |
<tr> | |
<th>Name</th> | |
<th>Location</th> | |
</tr> | |
</thead> | |
<tbody> | |
<?php foreach ($distributors as $distributor): ?> | |
<tr> | |
<td><?php echo $distributor->name; ?></td> | |
<td><?php echo $distributor->location; ?></td> | |
</tr> | |
<?php endforeach; ?> | |
</tbody> | |
</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
<?php | |
class GoogleDoc { | |
public function __construct($docId, $sheetId = 1) | |
{ | |
$this->docId = $docId; | |
$this->sheetId = $sheetId; | |
$this->json = file_get_contents('https://spreadsheets.google.com/feeds/list/' . $docId . '/' . $sheetId . '/public/values?alt=json'); | |
$this->response = json_decode($this->json); | |
} | |
public function getEntries() | |
{ | |
$entries = array(); | |
foreach ($this->response->feed->entry as $entry): | |
$entries[] = new GoogleDocEntry($entry); | |
endforeach; | |
return $entries; | |
} | |
} | |
class GoogleDocEntry { | |
public function __construct($entry) | |
{ | |
$this->object = $entry; | |
// clean up Google's content field with better delimiters | |
$delimited = preg_replace_callback( | |
'|, (\w+): |', | |
function($matches) | |
{ | |
return str_replace(', ', '<==>', $matches[0]); | |
}, | |
$this->object->content->{ '$t' } | |
); | |
// create an empty object to put the data in | |
$this->content = new stdClass; | |
// explode on the new delimiters | |
$data = explode('<==>', $delimited); | |
// loop through the data and explode it to get the keys and values | |
foreach ($data as $part) | |
{ | |
$pieces = explode(': ', $part); | |
// set the keys and values in the object we created earlier | |
$this->content->{ $pieces[0] } = $pieces[1]; | |
} | |
} | |
public function title() | |
{ | |
return $this->object->title->{ '$t' }; | |
} | |
public function __get($field) | |
{ | |
if (isset($this->object->{ 'gsx$' . $field })) | |
{ | |
return $this->object->{ 'gsx$' . $field }->{ '$t' }; | |
} | |
return $this->content->$field; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment