将Google Sheet转JSON仅读取99条数据?如何实现全量读取
解决Google Sheet转JSON仅读取99条数据的问题
原因分析
你遇到的是Google Sheets数据导出/API请求的默认行数限制问题——公开导出链接或旧版API端点默认最多返回100行(你看到99条可能是表头占用了一行)。要获取全量数据,需要通过参数调整或使用正确的API端点。
解决方案分两种场景处理:
场景1:使用公开表格的JSON导出链接(如https://spreadsheets.google.com/feeds/list/[表格ID]/[标签页]/public/values?alt=json)
这种方式默认限制100条,可通过添加参数突破限制:
单次获取指定行数
在请求URL中添加max-results参数,设置你需要的最大行数(比如1000):// Google API Key $apiKey = 'YOUR_API_KEY'; // 添加max-results参数指定最大返回行数 $urlWithKey = $url . '?key=' . $apiKey . '&max-results=1000'; echo "Fetching Data......"; $htmlData = file_get_contents($urlWithKey);分页获取超大量数据
如果数据超过1000条,循环使用start-index参数分页读取:$apiKey = 'YOUR_API_KEY'; $allData = []; $startIndex = 1; $maxResults = 1000; do { $urlWithKey = $url . "?key={$apiKey}&max-results={$maxResults}&start-index={$startIndex}"; $response = file_get_contents($urlWithKey); $data = json_decode($response, true); // 没有更多数据时退出循环 if (empty($data['feed']['entry'])) { break; } $allData = array_merge($allData, $data['feed']['entry']); $startIndex += $maxResults; } while (true); // $allData 包含所有行数据 print_r($allData);
场景2:使用Google Sheets API v4(推荐,更稳定)
改用v4 API端点,直接指定表格范围获取全量数据:
$apiKey = 'YOUR_API_KEY'; $spreadsheetId = '你的表格ID'; $range = 'Sheet1!A:Z'; // 指定整个标签页的所有列,可根据实际调整 $url = "https://sheets.googleapis.com/v4/spreadsheets/{$spreadsheetId}/values/{$range}?key={$apiKey}"; echo "Fetching Data......"; $response = file_get_contents($url); $data = json_decode($response, true); // $data['values'] 即为所有行的原始数据 print_r($data['values']);
额外注意事项
- 确保你的Google表格已设置为公开可访问(如果用API key访问私有表格,需要改用OAuth2认证);
- 如果使用v4 API,要确认你的API密钥已启用Google Sheets API服务(在Google Cloud控制台中配置)。
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

