This question already has answers here:
Using Google Books API
(2 answers)
Closed 5 years ago.
I have written a PHP code to parse the data pobidd by GoogleBooks API
<?php
$isbn = "9781451648546"; // Steve Jobs book
$json = file_get_contents('https://www.googleapis.com/books/v1/volumes?q=isbn:'.$isbn);
$obj = json_decode($json, true);
echo $obj["volumeInfo"]["title"];
echo $obj["volumeInfo"]["title"];
echo $obj["volumeInfo"]["subtitle"];
echo $obj["volumeInfo"]["authors"];
echo $obj["volumeInfo"]["printType"];
echo $obj["volumeInfo"]["pageCount"];
echo $obj["volumeInfo"]["publisher"];
echo $obj["volumeInfo"]["publishedDate"];
echo $obj["accessInfo"]["webReaderLink"];
?>
When execute it, I get
Notice: Undefined index: volumeInfo in /storage/ssd3/164/2474164/public_html/dev/fetch/v2.php on line 8
for all the echo strings , so I re-checked all possible sources of problem without solution
You're accessing the array elements in the wrong way. Do var_dump($obj); or echo '<pre>'; print_r($obj); echo '</pre>'; to see the complete array structure. Your echo statements would be like this:
echo $obj['items'][0]["volumeInfo"]["title"] . '<br />';
// echo $obj['items'][0]["volumeInfo"]["subtitle"];
echo $obj['items'][0]["volumeInfo"]["authors"][0] . '<br />';
echo $obj['items'][0]["volumeInfo"]["printType"] . '<br />';
echo $obj['items'][0]["volumeInfo"]["pageCount"] . '<br />';
echo $obj['items'][0]["volumeInfo"]["publisher"] . '<br />';
echo $obj['items'][0]["volumeInfo"]["publishedDate"] . '<br />';
echo $obj['items'][0]["accessInfo"]["webReaderLink"] . '<br />';
Not sure whether you would be getting subtitle information along with the book details. If so, then please uncomment that line.
To my mind it is far easier to use the object notation for accessing the various properties of the JSON response rather than the clunky array syntax but you need to identify the correct location in the object/array heirarchy before attempting to access the sub-keys of it.
$isbn = "9781451648546"; // Steve Jobs book
$json = file_get_contents('https://www.googleapis.com/books/v1/volumes?q=isbn:'.$isbn);
$obj = json_decode( $json );
$items=$obj->items;
foreach( $items as $item ){
/* Main keys */
$vol=$item->volumeInfo;
$sales=$item->saleInfo;
$access=$item->accessInfo;
$info=$item->searchInfo;
/* subkeys */
$title=$vol->title;
$authors=implode( $vol->authors );
$type=$vol->printType;
/* etc */
echo $title, $authors, $type, '<br />';//etc
}
/* to clearly see the data structure try this: */
echo '<pre>',print_r($obj,true),'</pre>';
Will output
Steve JobsWalter IsaacsonBOOK
stdClass Object
(
[kind] => books#volumes
[totalItems] => 1
[items] => Array
(
[0] => stdClass Object
(
[kind] => books#volume
[id] => 8U2oAAAAQBAJ
[etag] => Cfd5hfOLjks
[selfLink] => https://www.googleapis.com/books/v1/volumes/8U2oAAAAQBAJ
[volumeInfo] => stdClass Object
(
[title] => Steve Jobs
[authors] => Array
(
[0] => Walter Isaacson
)
[publisher] => Simon and Schuster
[publishedDate] => 2011
[description] => Draws on more than forty interviews with Steve Jobs, as well as interviews with family members, friends, competitors, and colleagues to offer a look at the co-founder and leading creative force behind the Apple computer company.
[industryIdentifiers] => Array
(
[0] => stdClass Object
(
[type] => ISBN_13
[identifier] => 9781451648546
)
[1] => stdClass Object
(
[type] => ISBN_10
[identifier] => 1451648545
)
)
[readingModes] => stdClass Object
(
[text] =>
[image] =>
)
[pageCount] => 630
[printType] => BOOK
[categories] => Array
(
[0] => Biography & Autobiography
)
[averageRating] => 4
[ratingsCount] => 3904
[maturityRating] => NOT_MATURE
[allowAnonLogging] =>
[contentVersion] => 0.3.0.0.preview.0
[imageLinks] => stdClass Object
(
[smallThumbnail] => http://books.google.com/books/content?id=8U2oAAAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api
[thumbnail] => http://books.google.com/books/content?id=8U2oAAAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api
)
[language] => en
[previewLink] => http://books.google.co.uk/books?id=8U2oAAAAQBAJ&printsec=frontcover&dq=isbn:9781451648546&hl=&cd=1&source=gbs_api
[infoLink] => http://books.google.co.uk/books?id=8U2oAAAAQBAJ&dq=isbn:9781451648546&hl=&source=gbs_api
[canonicalVolumeLink] => https://books.google.com/books/about/Steve_Jobs.html?hl=&id=8U2oAAAAQBAJ
)
[saleInfo] => stdClass Object
(
[country] => GB
[saleability] => NOT_FOR_SALE
[isEbook] =>
)
[accessInfo] => stdClass Object
(
[country] => GB
[viewability] => PARTIAL
[embeddable] => 1
[publicDomain] =>
[textToSpeechPermission] => ALLOWED_FOR_ACCESSIBILITY
[epub] => stdClass Object
(
[isAvailable] =>
)
[pdf] => stdClass Object
(
[isAvailable] =>
)
[webReaderLink] => http://play.google.com/books/reader?id=8U2oAAAAQBAJ&hl=&printsec=frontcover&source=gbs_api
[accessViewStatus] => SAMPLE
[quoteSharingAllowed] =>
)
[searchInfo] => stdClass Object
(
[textSnippet] => Draws on more than forty interviews with Steve Jobs, as well as interviews with family members, friends, competitors, and colleagues to offer a look at the co-founder and leading creative force behind the Apple computer company.
)
)
)
)
Related
I have an array returned from a json, I can access the values from one part of the array, but I can't access the values from another part of the array
echo '<strong>Barcode Number:</strong> ' . $response->products[0]->barcode_number . '<br><br>';
echo '<strong>Product Name:</strong> ' . $response->products[0]->product_name . '<br><br>';
echo '<strong>Description:</strong> ' . $response->products[0]->description . '<br><br>';
echo '<strong>Description:</strong> ' . $response->stores[0]->store_name . '<br><br>';
I get the first three fine but the last one for stores returns the error
Barcode Number: 077341125112
Product Name: Custom Accessories 89960W E-Tek Butane Torch
Description: Butane Torch, 89960W is ideal for your home garage or
your car. Can be used for quick repairs.
Notice: Undefined property: stdClass::$stores in
C:\xampp\htdocs\customs\production\test-barcodelookup.php on line 20
Notice: Trying to get property 'store_name' of non-object in
C:\xampp\htdocs\customs\production\test-barcodelookup.php on line 20
$ch = curl_init(); // Use only one cURL connection for multiple queries
$data = get_data($url, $ch);
$response = array();
$response = json_decode($data);
echo '<strong>Barcode Number:</strong> ' . $response->products[0]->barcode_number . '<br><br>';
echo '<strong>Product Name:</strong> ' . $response->products[0]->product_name . '<br><br>';
echo '<strong>Description:</strong> ' . $response->products[0]->description . '<br><br>';
echo '<strong>Description:</strong> ' . $response->stores[0]->store_name . '<br><br>';
echo '<strong>Entire Response:</strong><pre>';
print_r($response);
echo '</pre>';
function get_data($url, $ch) {
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
Below is the array returned
Entire Response:
stdClass Object
(
[products] => Array
(
[0] => stdClass Object
(
[barcode_number] => 077341125112
[barcode_type] => UPC
[barcode_formats] => UPC 077341125112, EAN 0077341125112
[mpn] => 0007734112511
[model] => 89960w
[asin] =>
[product_name] => Custom Accessories 89960W E-Tek Butane Torch
[title] =>
[category] => Hardware > Tools > Hardware Torches
[manufacturer] =>
[brand] => Etek
[label] =>
[author] =>
[publisher] =>
[artist] =>
[actor] =>
[director] =>
[studio] =>
[genre] =>
[audience_rating] =>
[ingredients] =>
[nutrition_facts] =>
[color] =>
[format] =>
[package_quantity] =>
[size] =>
[length] =>
[width] =>
[height] =>
[weight] =>
[release_date] =>
[description] => Butane Torch, 89960W is ideal for your home garage or your car. Can be used for quick repairs.
[features] => Array
(
)
[images] => Array
(
[0] => https://images.barcodelookup.com/3001/30014169-1.jpg
)
[stores] => Array
(
[0] => stdClass Object
(
[store_name] => Wal-Mart.com USA, LLC
[store_price] => 14.97
[product_url] => http://www.walmart.com/ip/Custom-Accessories-89960W-E-Tek-Butane-Torch/29029306
[currency_code] => USD
[currency_symbol] => $
)
[1] => stdClass Object
(
[store_name] => Jet.com
[store_price] => 14.20
[product_url] => http://jet.com/product/detail/a43035df304c4551b45f62262402f9f2
[currency_code] => USD
[currency_symbol] => $
)
)
[reviews] => Array
(
[0] => stdClass Object
(
[name] => Ken Weber
[rating] => 5
[title] => Torch Performance
[review] => I didnt know how good this torch was until I used it and its very nice for the money. The electronic ignition fires the butane evertime. Nice feel to it. Has a trigger lock down for extended usage time. GOOD PRODUCT.
[datetime] => 2015-12-29 11:27:34
)
)
)
)
)
I am trying to access the images array and echo it out and the information from the stores array and echo it. I can get the information from the products array. but I can't figure out how to get the others
This is what I am trying to achieve
Barcode Number: 077341125112
Product Name: Custom Accessories 89960W E-Tek Butane Torch
Description: Butane Torch, 89960W is ideal for your home garage or
your car. Can be used for quick repairs.
Display Image of product.
Stores:
store_name: Wal-Mart.com USA, LLC store_price: 14.97 product_url:
http://www.walmart.com/ip/Custom-Accessories-89960W-E-Tek-Butane-Torch/29029306
store_name: Jet.com store_price: 14.20 product_url:
http://jet.com/product/detail/a43035df304c4551b45f62262402f9f2
When you format the data, it shows that the stores data is under each product, so you would need to display it as...
$response->products[0]->stores[0]->store_name
You would also probably need to use a foreach() to display all the details, both with products and the stores for each product.
foreach ( $response->products[0]->stores as $store ) {
// Echo out the details
echo $store->store_name;
}
Side-step: I think the easiest way to go about this process is using
json_decode($json, true);
This makes everything an associative array.
Here is the manual for the json_decode internal function.
Step-back:
$response->products[0]->stores[0]->store_name
This is my example json data
[
{"kode":"AX5","harga":"6200","status":"1","nama":"AXIS 5"},
{"kode":"AX10","harga":"11250","status":"1","nama":"AXIS 10"},
{"kode":"AX25","harga":"25750","status":"1","nama":"AXIS 25"},
{"kode":"AX50","harga":"50800","status":"1","nama":"AXIS 50"}
]
and i want to save the data to mysql with php, field product_id, price, status, name, anyone can help me please
my problem is, i dont know better code for me in php
You could use PHP
json_decode()
function to convert that json string into PHP variables.
You could then get those values and save them to the MySQL Database;
Source json_decode PHP Manual
you can use json_decode(). it takes a JSON encoded string and converts it into a PHP variable.
<?php
$json_data = '[{"kode":"AX5","harga":"6200","status":"1","nama":"AXIS 5"},{"kode":"AX10","harga":"11250","status":"1","nama":"AXIS 10"},{"kode":"AX25","harga":"25750","status":"1","nama":"AXIS 25"},{"kode":"AX50","harga":"50800","status":"1","nama":"AXIS 50"}]';
$array_data = json_decode($json_data);
echo '<pre>';
print_r($array_data);
foreach ($array_data as $event) {
echo 'Product_id:' . $event->kode;
echo "<br>";
echo 'status:' . $event->status;
echo "<br>";
}
then output is
Array
(
[0] => stdClass Object
(
[kode] => AX5
[harga] => 6200
[status] => 1
[nama] => AXIS 5
)
[1] => stdClass Object
(
[kode] => AX10
[harga] => 11250
[status] => 1
[nama] => AXIS 10
)
[2] => stdClass Object
(
[kode] => AX25
[harga] => 25750
[status] => 1
[nama] => AXIS 25
)
[3] => stdClass Object
(
[kode] => AX50
[harga] => 50800
[status] => 1
[nama] => AXIS 50
)
)
Product_id:AX5
status:1
Product_id:AX10
status:1
Product_id:AX25
status:1
Product_id:AX50
status:1
for more information
http://php.net/manual/en/function.json-decode.php
I'l try to get the movie title and info from the omdb API. This is my code:
<?php
$enter = $_GET["enter"];
$content = file_get_contents("https://www.omdbapi.com/?s=$enter&r=xml");
$xml = simplexml_load_string($content);
if($xml) {
echo "<h2>" .$xml->title. "</h2>";
}
else
{
echo "Nothing found. Add the info manualy";
}
?>
The "enter" value is from the search form with AJAX. He create only an empty h2 tag. How can i get also the data from the API?
Thank you,
Julian
You should familiarize yourself with the structure of the xml to know how to access its elements. print_r(get_object_vars($xml)) will show you a structure like this:
Array
(
[#attributes] => Array
(
[totalResults] => 3651
[response] => True
)
[result] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[title] => World War Z
[year] => 2013
[imdbID] => tt0816711
[type] => movie
[poster] => https://images-na.ssl-images-amazon.com/images/M/MV5BMTg0NTgxMjIxOF5BMl5BanBnXkFtZTcwMDM0MDY1OQ##._V1_SX300.jpg
)
)
[1] => SimpleXMLElement Object
(
[#attributes] => Array
(
[title] => Captain America: Civil War
[year] => 2016
[imdbID] => tt3498820
[type] => movie
[poster] => https://images-na.ssl-images-amazon.com/images/M/MV5BMjQ0MTgyNjAxMV5BMl5BanBnXkFtZTgwNjUzMDkyODE#._V1_SX300.jpg
)
)
...
...
...
[9] => SimpleXMLElement Object
(
[#attributes] => Array
(
[title] => War
[year] => 2007
[imdbID] => tt0499556
[type] => movie
[poster] => https://images-na.ssl-images-amazon.com/images/M/MV5BMTgzNTA4MTc3OF5BMl5BanBnXkFtZTcwOTA0ODk0MQ##._V1_SX300.jpg
)
)
)
)
So you receive an array with results where you need to pick from. Alternatively if you know the exact title the API has the t=title option which only returns a single result (see documentation).
So assuming you use the s=title option which returns multiple results, you can use something like this to pick information from the first result:
<?php
$enter = $_GET["enter"];
$content = file_get_contents("https://www.omdbapi.com/?s=$enter&r=xml");
$xml = simplexml_load_string($content);
# show the structure of the xml
# print_r(get_object_vars($xml));
if($xml) {
print "<h2>" .$xml->result[0]['title']. "</h2>";
print "<br>imdbID=" . $xml->result[0]['imdbID'] ;
} else {
echo "Nothing found. Add the info manualy";
}
?>
I am retrieving a multidimensional php array (I think) from an API, now all of the values return perfectly and when I dump the array with print_r I get this:
Event Object
(
[title] => test
[link] => google.com
[updated] => 2013-03-06T12:08:56.521-05:00
[id] => test
[name] => Copy of Copy of Copy of Mar 05, 2013 - TEST4
[description] =>
[registered] => 2
[createdDate] => 2013-03-06T12:08:56.521-05:00
[status] => COMPLETE
[eventType] => OTHER
[eventLocation] => EventLocation Object
(
[location] => test
[addr1] => test
[addr2] =>
[addr3] =>
[city] => madrid
[state] => andalucia
[country] =>
[postalCode] => 06103
)
[registrationUrl] => https://google.com
[startDate] => 2013-03-07T13:00:00-05:00
[endDate] => 2013-03-07T13:00:00-05:00
[publishDate] => 2013-03-06T12:11:15.958-05:00
[attendedCount] => 0
[cancelledCount] => 0
[eventFeeRequired] => FALSE
[currencyType] => USD
[paymentOptions] => Array
(
)
[registrationTypes] => Array
(
[0] => RegistrationType Object
(
[name] =>
[registrationLimit] =>
[registrationClosedManually] =>
[guestLimit] =>
[ticketing] =>
[eventFees] => Array
(
)
)
)
)
Now bumbling through wit my basic PHP i have found that i can list all of the first array items from [title] to [eventType] like this:
<?php
// get details for the first event returned
$Event = $ConstantContact->getEventDetails($events['events'][0]);
reset($Event);
while (list($key, $value) = each($Event)) {
echo "$key => $value \r\n<br/>";
}
?>
my question: All I need to do it retrieve [title] and [startDate] I don't need the rest now I could just hide the rest using Js and css but i am sure i am just being an idiot and there is an easier way to traverse this array so it only spits out the two values i need.
How do i do this?
You do not have to traverse the whole object. Just access the properties you want:
$title = $Event->title;
$startDate = $Event->startDate;
// or
echo $Event->title;
echo $Event->startDate;
It's actually an object - not an (associative) array!
What's the difference?
An object is an instance of a class. A class has methods and attributes (member variables).
Unlike C++ or some other OOP languages, you can define attributes dynamically without declaring them in the class declaration.
An array is simply a container for keys and their values.
It seems that it's not an array but an object so something like this:
echo $Event->title;
echo $Event->startDate;
Is it ...
<?php
// get details for the first event returned
$Event = $ConstantContact->getEventDetails($events['events'][0]);
reset($Event);
echo $Event->$title . "<br/>";
echo $Event->$startDate . "<br/>";
?>
? Or am I too simple?
I'm pulling in a list of my vimeo albums using the Vimeo API and the looping three times through the array to get to the albums. It works fine.
My question is, I'm isolating the date, so how can I create a new array and sort it by the date?
While where at it, is there a way to jump to the third level of a multi-dimensional array?
$albums=$vimeo->call('vimeo.albums.getAll', array('user_id' => $myUserId));
$albums_array=object_2_array($albums);
foreach($albums_array as $album_array_two){
foreach($album_array_two as $album_array_three){
foreach($album_array_threeas $album){
if(stristr($album['title'],'conference')){
$title=$album['title'];
$description=$album['description'];
$date=stristr($album['description'],'.',true);
$year_comma=stristr($date,',');
$year=ereg_replace("[^0-9]", "", $year_comma);
$url_title='http://www.psfk.com/events/'.str_replace( " ", "-", strtolower($title));
$url=''.$title.'';
$thumb=$album['thumbnail_video']['thumbnails']['thumbnail'][1]['_content'];
echo '<li class="album">';
echo '<img src="'.$thumb.'" alt="'.$title.'" />';
echo '<div class="info">';
echo '<h2>'.$url.'</h2>';
echo $description.'<br />';
echo 'View...';
echo '</div></li>';
}
}
}
}
Sample of the array returning one item:
Array (
[generated_in] => 0.0828
[stat] => ok
[albums] => Array (
[on_this_page] => 7
[page] => 1
[perpage] => 50
[total] => 7
[album] => Array (
[0] => Array (
[id] => 1690236
[title] => Interviews
[description] =>
[created_on] => 2011-09-10 21:43:49
[total_videos] => 1
[url] => Array (
[0] => http://vimeo.com/album/1690236
)
[video_sort_method] =>
[thumbnail_video] => Array (
[id] => 28825158
[owner] => 718882
[title] => Where Inspiration Comes From [thumbnails] => Array (
[thumbnail] => Array (
[0] => Array (
[height] => 75
[width] => 100
[_content] => http://b.vimeocdn.com/ts/192/593/192593029_100.jpg
)
)
)
)
)
)
)
)
In order to sort by date, you can use the php_function array_multisort(). There is a good example on that page that I think shows what you need. I'll try to provide a better example using your data. Suppose after looping through your albums you end up with an array $myAlbums that looks like this:
Array (
[0] => Array(
[title] => My Title
[description] => some description
[date] 01-05-2011
)
[1] => Array(
.......
)
In order to sort this by date, you could do the following (taken from the example on the php page)
<?php
// Obtain a list of columns
foreach ($myAlbums as $key => $row) {
$date[$key] = $row['date'];
}
// Sort the data with volume descending, edition ascending
// Add $myAlbums as the last parameter, to sort by the common key
array_multisort($date, SORT_DESC, $myAlbums);
?>
Then you can print_r($myAlbums); and you should see that it is sorted. You might have to change the SORT_DESC flag depending on what formate your dates are in. I can't really explain HOW this works, because I'm still trying to figure it out myself... but I think it is what you need.