Google Books API возвращает только 10 результатов

Я впервые внедряю PHP-приложение, которое требует некоторых данных из Google Books API. Это довольно неудобно, но когда я использую типичный запрос http://books.google.com/books/feeds/volumes?q=search + термин (кто-то, кто имеет предыдущий опыт работы с конкретным API, может понять меня), он возвращает только 10 результатов.

например, ответ XML для http://books.google.com/books/feeds/volumes?q=php, содержит следующее поля: между totalresults>582. Однако я получаю только 10.

после прочтения соответствующей документации я не пришел к решению.

кто-нибудь может мне помочь?

2 ответов


нет, это еще один парам:max-results. Но похоже, что максимальное количество результатов на одной "странице" по - прежнему довольно низкое-20.

например, такой запрос:

http://books.google.com/books/feeds/volumes?q=php&max-results=40

... дал мне всего 20 записей. Полезно, однако, что вы можете перебирать коллекцию с помощью start-index param, как это:

http://books.google.com/books/feeds/volumes?q=php&max-results=20&start-index=21

... затем 41, 61 и т. д. Она начинается с 1, а не 0, я проверил. )


в настоящее время ключевое слово maxResults, а не max-results как в ответе raina77ow. источник. Как говорится в документации, максимальное количество книг, которые можно получить сразу, составляет 40. Однако вы можете преодолеть это ограничение с помощью нескольких запросов, например, с помощью этой PHP-функции:

private $books = array('items' => array());

/**
 * Searches the Google Books database through their public API
 * and returns the result. Notice that this function will (due to
 * Google's restriction) perform one request per 40 books.
 * If there aren't as many books as requested, those found will be
 * returned. If no books at all is found, false will be returned.
 * 
 * @author Dakniel
 * @param string $query Search-query, API documentation
 * @param int $numBooksToGet Amount of results wanted
 * @param int [optional] $startIndex Which index to start searching from
 * @return False if no book is found, otherwise the books
 */
private function getBooks($query, $numBooksToGet, $startIndex = 0) {

    // If we've already fetched all the books needed, or
    // all results are already stored
    if(count($this->books['items']) >= $numBooksToGet)
        return $this->books;

    $booksNeeded = $numBooksToGet - count($this->books['items']);

    // Max books / fetch = 40, this is therefore our limit
    if($booksNeeded > 40)
        $booksNeeded = 40;

    $url = "https://www.googleapis.com/books/v1/volumes?q=". urlencode($query) ."&startIndex=$startIndex&maxResults=$booksNeeded";

    // Get the data with cURL
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    $bookBatch = curl_exec($ch);
    curl_close($ch);

    // If we got no matches..
    if($bookBatch['totalItems'] === 0) {

        // .. but we already have some books, return those
        if(count($this->books) > 0)
            return $this->books;
        else
            return false;

    }

    // Convert the JSON to an array and merge the existing books with
    // this request's new books 
    $bookBatch = json_decode($bookBatch, true);
    $this->books['items'] = array_merge($this->books['items'], $bookBatch['items']);

    // Even if we WANT more, but the API can't give us more: stop
    if( ($bookBatch['totalItems'] - count($this->books['items'])) === 0 ) {
        return $this->books;
    }

    // We need more books, and there's more to get: use recursion
    return $this->getBooks($query, $numBooksToGet, $startIndex);

}

простой пример использования:

$books = $this->getBooks("programming", 50);

что вернет до 50 книг, которые соответствуют программирование сайта. Надеюсь, кто-то будет использовать удачи вам в этом!