Scoobler
Scoobler

Reputation: 9719

PHP / Zend / Google Spreadsheet not getting all rows

I am trying to get all the rows from a Google spreadsheet via a PHP/Zend script. This is the script I am using:

    $service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
    $client = Zend_Gdata_ClientLogin::getHttpClient('xxxxxxxxx', 'xxxxxxx', $service);
    $spreadsheetService = new Zend_Gdata_Spreadsheets($client);

    // Get spreadsheet key
    $spreadsheetsKey = 'xxxxxxxxxxxxx';   
    $worksheetId = 'xxx';

    // Get cell feed
    $query = new Zend_Gdata_Spreadsheets_CellQuery();
    $query->setSpreadsheetKey($spreadsheetsKey);
    $query->setWorksheetId($worksheetId);
    $cellFeed = $spreadsheetService->getCellFeed($query);

    // Build an array of entries:
    $ssRows = array();
    $ssRow = array();
    $titleRow = array();

    $tableRow = 1;
    foreach($cellFeed as $cellEntry) {
        $row = $cellEntry->cell->getRow();
        $col = $cellEntry->cell->getColumn();
        $val = $cellEntry->cell->getText();
        // Add each row as a new array:
        if ($row != $tableRow) {
            array_push($ssRows, $ssRow);
            $ssRow = array();
            // Move to the next row / new array
            $tableRow = $row;
        }
        // Build the array of titles:
        if ($row == 1) {
            $titleRow[$col] = $val;
        } 
        // Build the array of results with the title as the key:
        else {
            $key = $titleRow[$col];
            $ssRow[$key] = $val;                
        }
    }

    // Pass the results array:
    return array_reverse($ssRows);

This builds me an array with MOST of the details from the spreadsheet, however it always misses off the last entry - can anyone see what I am doing wrong, or is there a better way to get all the data from the spreadsheet?

The form is a 3 part form, based on different answers. On filling out one part, I want to display a URL back to the form, with some details from the first form pre-filled to make the second part of the form faster to fill out. This is all fine, it is simply the missing last entry that is the major problem!

Thanks!

Upvotes: 0

Views: 321

Answers (1)

Halcyon
Halcyon

Reputation: 57719

Your code works like this:

if (next_row) {
    data[] = current_row
    current_row = array();
}
if (first_row) {
    title_row logic
} else {
    add cell to current_row
}

So you only add the rows to your collector once you go to the next row. This will miss the last row because you'll miss that last transition.

The easy fix is to add array_push($ssRows, $ssRow); right after the foreach loop. You will need to add a check for 0 rows, this should be skipped then.


Perhaps a more proper fix is to iterate by row, then by cell, rather than just by cell.

Upvotes: 1

Related Questions