Shopify REST Admin API响应头无下一页URL问题排查求助
Shopify REST Admin API 分页无法获取Link响应头问题解决
问题根源
你当前代码里用curl_getinfo($ch)只能获取cURL请求的元数据(比如HTTP状态码、请求耗时等),无法获取完整的HTTP响应头,这就是找不到分页所需的Link头的核心原因。另外你的循环逻辑每次都请求第一页,没有实现分页迭代。
解决方案
- 修改cURL配置,获取完整响应头
通过设置cURL参数让请求返回包含响应头的内容,之后从响应头中提取Link字段。 - 实现正确的分页循环逻辑
解析Link头里的next链接,作为下一次请求的URL,直到响应头中不再包含next链接时终止循环。
修正后的完整代码
$productEndpoint = "https://".$this->shop."/admin/api/2024-01/products.json"; $perPage = 20; $allProducts = []; $nextUrl = $productEndpoint . "?limit=" . $perPage; do { $ch = curl_init($nextUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, true); // 让响应包含头信息 curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'X-Shopify-Access-Token: ' . $this->accessToken, ]); $fullResponse = curl_exec($ch); $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); // 拆分响应头和响应体 $rawHeaders = substr($fullResponse, 0, $headerSize); $responseBody = substr($fullResponse, $headerSize); $nextUrl = null; // 解析响应头提取next链接 foreach (explode("\r\n", $rawHeaders) as $line) { if (strpos($line, 'Link:') === 0) { $linkHeader = trim(substr($line, 5)); preg_match('/<([^>]+)>; rel="next"/', $linkHeader, $matches); $nextUrl = $matches[1] ?? null; break; } } $productDataArray = json_decode($responseBody, true); if (!empty($productDataArray['products'])) { $allProducts = array_merge($allProducts, $productDataArray['products']); } curl_close($ch); } while ($nextUrl !== null); // 所有商品已存入$allProducts // var_dump($allProducts);
关键说明
- 响应头解析:通过正则匹配Link头中的
rel="next"链接,确保每次请求下一页的正确地址。 - 循环终止条件:当响应头中没有
next链接时,说明已经获取完所有数据,终止循环。 - 响应拆分:利用
CURLINFO_HEADER_SIZE拆分响应头和响应体,避免头信息干扰JSON解析。
内容的提问来源于stack exchange,提问作者sam707
相关产品推荐
相关产品推荐

