upinson
upinson

Reputation: 11

Error Parsing Google Book JSON API with PHP

I am stuck now, I tried to parse JSON API Google Book using PHP.

this is my PHP

    <?php
$api = 'AIzaSyB2__dPng5IGT9Nlca0UT7FxN459mrITmo';
$book_api = file_get_contents('https://www.googleapis.com/books/v1/volumes?q=fift+shades+of+grey&key='.$api);
$book = json_decode($book_api);
$a = $book->items;
$results = $a->volumeInfo;
$images = $results->imageLinks;

foreach ($results as $result) {
        $title = $result->title;
        $author = $result->authors;
        $desc = $result->description;
        $cat = $result->categories;
        $pages = $result->pageCount;
}
foreach ($images as $image) {
        $thumb = $image->thumbnail;
}
?>
<html>
<head>
<title>Exampe API Google Book</title>
</head>
<body>
<h1><?php echo $title; ?></h1><br/>
<?php echo $desc; ?>

</body>
</html>

I get error

Notice: Trying to get property of non-object in

and

Warning: Invalid argument supplied for foreach() in

I want to use to display the search results book.

Can you help me to fix it?

Thanks

Upvotes: 0

Views: 172

Answers (2)

Hassaan
Hassaan

Reputation: 7682

You were not selecting the right property of array. I have given a complete solution for your reference below. You really don't need two loops for it.

<?php
$api = 'AIzaSyB2__dPng5IGT9Nlca0UT7FxN459mrITmo';
$book_api = file_get_contents('https://www.googleapis.com/books/v1/volumes?q=fift+shades+of+grey&key='.$api);
$book = json_decode($book_api);
$meta_data = $book->items;
?>
<html>
<head>
<title>Exampe API Google Book</title>
</head>
<body>
<?php

for($i = 0; $i < count($meta_data); $i++)
{
    $title = $meta_data[$i]->volumeInfo->title;
    $author = $meta_data[$i]->volumeInfo->authors;
    $desc = $meta_data[$i]->volumeInfo->description;
    $cat = @$meta_data[$i]->volumeInfo->categories;
    $pages = @$meta_data[$i]->volumeInfo->pageCount;
    $thumb = $meta_data[$i]->volumeInfo->imageLinks->thumbnail;

    echo "<h1>$title</h1><br/>";
    echo "<p><img src=\"$thumb\" style=\"float:left; padding: 10px;\">$desc</p><br clear=\"all\" /><hr />";
}

?>

</body>
</html>

Upvotes: 1

Kamehameha
Kamehameha

Reputation: 5488

If you look at your resulting json -

...
items": [
  {
   "kind": "books#volume",
   "id": "V1Re
...

This $a = $book->items; returns an array.
So doing this is wrong -

$results = $a->volumeInfo;

You need to iterate through $a using a foreach and get each individual volumeInfo and modify the rest of your code accordingly

Upvotes: 0

Related Questions