Search code examples
jsoncurlgoogle-books

Trouble getting Google Books API data via PHP


The current code takes form input and does THIS to it:

$apikey = 'myapikey';
$q = urlencode($bookSearchTerm);
$endpoint = 'https://www.googleapis.com/books/v1/volumes?q=' . $q . '&key=' . $apikey;
$session = curl_init($endpoint);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($session);
curl_close($session);
$search_results = json_decode($data);
if ($search_results === NULL) die('Error parsing json');

Just for kicks, I also did

echo $endpoint;

which shows

https://www.googleapis.com/books/v1/volumes?q=lord+of+the+rings&key=myapikey

When I enter that URL into a browser, I get a screen full o' data, telling me that, among other things, there are 814 items.

Yet when I run the code on a page, I get

Error parsing json

Can someone show me where I'm going wrong?

Thanks in advance.


Solution

  • By the response to the comment, it could be set, maybe not. It may also be the case that what is returned isn't parse-able by the parser because it isn't in the right data format. Check what $data gives back as a result. If it's correct then by the json_decode doc on the PHP site it may be that it's simply too big for the parser to parse (reaches recursion limit) though I doubt that.

    It it is possible that the what is return just overflows the PHP allocated memory limit. PHP parses JSON into associative or numbered arrays, which can get expensive. So if what you get back is just too big, it'll fail to finish parsing and just return null.