print random row from Google Spreadsheet via php
I would like to create a PHP script that fetches a few rows from a Google Spreadsheets and display it in html.
$authService = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$httpClie开发者_如何学JAVAnt = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $authService);
$gdClient = new Zend_Gdata_Spreadsheets($httpClient);
$feed = $gdClient->getSpreadsheetFeed('https://spreadsheets.google.com/ccc?key=MY_DOC_KEY');
$currKey = explode('/', $feed->entries[0]->id->text);
$query = new Zend_Gdata_Spreadsheets_CellQuery();
$query->setSpreadsheetKey($this->currKey);
$query->setWorksheetId($this->currWkshtId);
$query->setMinCol(1);
$query->setMaxCol(7);
$query->setMinRow(2);
$feed = $gdClient->getCellFeed($query);
However that throws a really ugly error message. What am i doing wrong?
Fatal error: Uncaught exception 'Zend_Gdata_App_Exception' with message 'DOMDocument cannot parse XML: DOMDocument::loadXML() Extra content at the end of the document in Entity, line: 23'
Short answer:
Why do you want to list the spreadsheets if you already know which spreadsheet you want to read from?
Long answer:
I am new to both Zend and Gdata, but tried to run your code and got the same exception. But after reading the docs (http://framework.zend.com/manual/en/zend.gdata.spreadsheets.html) I've tried replacing:
$feed = $gdClient->getSpreadsheetFeed('https://spreadsheets.google.com/ccc?key=MY_DOC_KEY');
with:
$feed = $gdClient->getSpreadsheetFeed();
and after adding the obvious:
foreach($feed as $cellEntry) {
$row = $cellEntry->cell->getRow();
$col = $cellEntry->cell->getColumn();
$val = $cellEntry->cell->getText();
echo "$row, $col = $val\n";
}
I got some data.
Then I understood, these two lines are not needed at all:
$feed = $gdClient->getSpreadsheetFeed('https://spreadsheets.google.com/ccc?key=MY_DOC_KEY');
$currKey = explode('/', $feed->entries[0]->id->text);
So getSpreadsheetFeed
is useful if you want to list/filter spreadsheets (and then there's no point in suplying the key) and to read the data from the known spreadsheet it's enough to use just the Zend_Gdata_Spreadsheets_CellQuery
.
Now I learned something.
I managed to realize the script via a Google Spreadsheets class that wraps around the Zend Gdata class and makes it a lot easier to use.
Here is the functional code:
$ss = new Google_Spreadsheet($user,$password);
$ss->useSpreadsheet("My Spreadsheet");
$ss->useWorksheet('Sheet1');
$rows = $ss->getRows();
if ($rows){
$data = returnRandomElement($rows);
echo 'NonBullshitCollectiveWidget.serverResponse('.json_encode($data).')';
}
else {
echo 'NonBullshitCollectiveWidget.serverResponse({"columnName":"Error!"})';
}
function returnRandomElement($array){
return $array[array_rand($array,1)];
}
精彩评论