1

So, I'm fairly new to working with APIs, and am just trying to play around with using the Etsy API to display a certain set of listings.

By default, the API returns a set of 25 results, and can do a max of 100 at a time. I'd like to show more than that, so I'm trying to add pagination to my call. Here's what I've got so far:

<?php

//setting API key

define("API_KEY", XXX);

//setting request url

$url = "https://openapi.etsy.com/v2/listings/active?keywords=unicorn,unicorns&includes=Images:1:0&api_key=" . API_KEY;

while (isset($url) && $url != '') {

        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $response_body=curl_exec($curl);
        curl_close($curl);

        $response = json_decode($response_body);

        foreach ($response->results as $listing) {
                echo "<li>" . $listing->title . " ~*~ " . $listing->price . " " . $listing->currency_code . " ~*~ " . '<a href="' . $listing->url . '" target="_blank">View on Etsy!</a>' . "</li>" . "<br>";
        }

        $url = $response->pagination->next_page;
}

?>

I thought this would loop through and return the next set of 25 results, but it didn't. Anyone have experience working with this? Is there somewhere I'm getting tripped up?

Thanks!

4

1 回答 1

1

在您的while块中,您将next_page属性的值分配给$url.
但实际值为int2,而不是 url。
而是将 附加next_page到初始 url,作为查询字符串变量。

$url .= "&page=" . $response->pagination->next_page;

请参阅下面的示例,了解如何将每个进程隔离到一个函数。

我们将curl操作移到它自己的函数中,它从json_decode.

我们将列表的整个处理转移到一个单独的函数中,现在它只是打印出列表。

第二个函数是递归的,这意味着如果下一页存在,它将调用第一个函数,获取响应,然后处理它。

<?php
//setting API key

define("API_KEY", 'br4j52uzdtlcpp6qxb6we3ge');

function get_listings($page=1){

    $url = "https://openapi.etsy.com/v2/listings/active?keywords=unicorn,unicorns&includes=Images:1:0&api_key=" . API_KEY;

    $url .= "&page=$page";

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $response_body=curl_exec($curl);
    curl_close($curl);

    $responseObject = json_decode($response_body);
    return $responseObject;
}

function process_listings($responseObject){

    foreach ($responseObject->results as $listing) {
        echo "Title: " . $listing->title . PHP_EOL . 
            "Price " . $listing->price . PHP_EOL . 
            "Currency code " . $listing->currency_code . PHP_EOL . 
            'URL ' . $listing->url . PHP_EOL;
    }

    print PHP_EOL . "Pagination " . $responseObject->pagination->next_page . PHP_EOL;
    $next_page = $responseObject->pagination->next_page;
    if ($next_page) {
        $nextPageResponse = get_listings($next_page);
        process_listings($nextPageResponse);
    }
}

$firstPage = get_listings(); // page 1 is default
process_listings($firstPage);
于 2015-12-01T11:54:18.780 回答