Google Books API data as PHP array? - php

I get the following response from the google:
{
"kind": "books#volumes",
"totalItems": 1,
"items": [
{
"kind": "books#volume",
"id": "t9S82uKGp8IC",
"etag": "rn9INXAtx88",
"selfLink": "https://www.googleapis.com/books/v1/volumes/t9S82uKGp8IC",
"volumeInfo": {
"title": "Classic Swedish Interiors",
"authors": [
"Lars Sjöberg",
"Ingalill Snitt"
],
"publisher": "Frances Lincoln Ltd",
"publishedDate": "2010-09-07",
"description": "Lars Sjöberg has made it his life's work to understand and preserve the Swedish manor houses of the 17th and 18th centuries. Here, exquisitely photographed by Ingalill Snitt, are the eight houses (and one church) that he has acquired over more than 40 years. The book focuses on Sjöberg's first, most complex project: the manor of Regnaholm. Unoccupied for about 40 years when Sjöberg arrived in 1966, it allowed him to experiment with interior decoration and refurnishing, copying old furniture, reweaving, and reprinting old fabric patterns. His other projects include Ekensberg, a three-story Italianate villa near Lake Mälaren, built in 1788-90, and Salaholm in Västergötland with a garden laid out in the first half of the 17th century. Odenslunda, a small manor from the 1770s with a panelled exterior and a säteritak or manor-house roof, is his family home, while Sörby, a scaled-down early 17th-century manor house, was reproduced in its entirety for an exhibition in Stockholm. Full of insight and inspiration, this is a deeply personal summary of everything Lars Sjöberg has learned in his years of working and living with classic Swedish interiors.",
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "0711230889"
},
{
"type": "ISBN_13",
"identifier": "9780711230880"
}
],
"pageCount": 208,
"printType": "BOOK",
"categories": [
"Architecture"
],
"contentVersion": "preview-1.0.0",
"imageLinks": {
"smallThumbnail": "http://bks8.books.google.com/books?id=t9S82uKGp8IC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
"thumbnail": "http://bks8.books.google.com/books?id=t9S82uKGp8IC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
},
"language": "en",
"previewLink": "http://books.google.com/books?id=t9S82uKGp8IC&printsec=frontcover&dq=isbn:9780711230880&cd=1&source=gbs_api",
"infoLink": "http://books.google.com/books?id=t9S82uKGp8IC&dq=isbn:9780711230880&source=gbs_api",
"canonicalVolumeLink": "http://books.google.com/books/about/Classic_Swedish_Interiors.html?id=t9S82uKGp8IC"
},
"saleInfo": {
"country": "ZA",
"saleability": "NOT_FOR_SALE",
"isEbook": false
},
"accessInfo": {
"country": "ZA",
"viewability": "PARTIAL",
"embeddable": true,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED_FOR_ACCESSIBILITY",
"epub": {
"isAvailable": false
},
"pdf": {
"isAvailable": true,
"acsTokenLink": "http://books.google.com/books/download /Classic_Swedish_Interiors-sample-pdf.acsm?id=t9S82uKGp8IC&format=pdf&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
},
"webReaderLink": "http://books.google.com/books/reader?id=t9S82uKGp8IC& printsec=frontcover&output=reader&source=gbs_api",
"accessViewStatus": "SAMPLE"
},
"searchInfo": {
"textSnippet": "Full of insight and inspiration, this is a deeply personal summary of everything Lars Sjöberg has learned in his years of working and living with classic Swedish interiors."
}
}
]
What is this format called? (It's not XML or JSON?)
How do I convert this text into an PHP array?

It's JSON. You can use json_decode() to convert it into a PHP associative array.
$books = json_decode($your_json_data, true);
print_r($books);

Related

How do i Parsing JSON in Php Seprate and loop through data

Hey,
I wanted to know that I am using an API, That API gives me the news in JSON format. Now I am making a Website that will have all those news. I cannot parse this JSON DATA, This is the URL that contains this data.
JSON LINK
{
"status": "ok",
"totalResults": 20,
"articles": [
{
"source": {
"id": "the-new-york-times",
"name": "The New York Times"
},
"author": "http://www.nytimes.com/by/jonah-engel-bromwich, https://www.nytimes.com/by/vanessa-friedman, https://www.nytimes.com/by/matthew-schneier",
"title": "Kate Spade, American Designer, Is Dead at 55",
"description": "Ms. Spade was discovered in her apartment in Manhattan.",
"url": "https://www.nytimes.com/2018/06/05/fashion/kate-spade-dead.html",
"urlToImage": "https://static01.nyt.com/images/2018/06/06/fashion/06spade/06spade-facebookJumbo.jpg",
"publishedAt": "2018-06-05T17:00:36Z"
},
{
"source": {
"id": "the-washington-post",
"name": "The Washington Post"
},
"author": "https://www.facebook.com/amber.j.phillips",
"title": "Paul Manafort could now be in even more trouble. That should worry Trump.",
"description": "More legal pressure on Manafort=more chance he'll flip in the Russia investigation.",
"url": "https://www.washingtonpost.com/news/the-fix/wp/2018/06/05/paul-manafort-could-now-be-in-even-more-trouble-that-should-worry-trump/",
"urlToImage": "https://www.washingtonpost.com/resizer/0YVxgDU7BlAuRmQ80mc3miYo5CI=/1484x0/arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/J3ICKYJOMQ6CNHGVZIHSRNPL7Y.jpg",
"publishedAt": "2018-06-05T16:51:02Z"
},
{
"source": {
"id": "reuters",
"name": "Reuters"
},
"author": "Laila Bassam",
"title": "Exclusive: In Syria, a Russian move causes friction with Iran-backed forces - officials",
"description": "A Russian troop deployment in Syria near the Lebanese border this week caused friction with Iran-backed forces including Hezbollah which objected to the uncoordinated move, two non-Syrian officials in the regional alliance backing Damascus said.",
"url": "https://www.reuters.com/article/us-mideast-crisis-syria-russia-deploymen/exclusive-in-syria-a-russian-move-causes-friction-with-iran-backed-forces-officials-idUSKCN1J125S",
"urlToImage": "https://s4.reutersmedia.net/resources_v2/images/rcom-default.png",
"publishedAt": "2018-06-05T16:20:59Z"
},
{
"source": {
"id": null,
"name": "Nbcsports.com"
},
"author": "https://www.facebook.com/RoobCSN/",
"title": "White House drama could have destroyed other teams … but not these Eagles",
"description": "All this White House drama could have destroyed other teams, but unity is what makes these Eagles so special. By Reuben Frank",
"url": "https://www.nbcsports.com/philadelphia/eagles/white-house-drama-could-have-destroyed-other-teams-not-these-eagles",
"urlToImage": "https://www.nbcsports.com/philadelphia/sites/csnphilly/files/2018/06/05/us_eagles_link_arms.jpg",
"publishedAt": "2018-06-05T16:17:21Z"
},
{
"source": {
"id": "newsweek",
"name": "Newsweek"
},
"author": "Marie Solis",
"title": "Bill Clinton Says He Got 'Hot Under the Collar' Answering Questions About Monica Lewinsky and #MeToo",
"description": "Bill Clinton said he got \"hot under the collar\" when he answered questions about Monica Lewinsky on the Today show.",
"url": "http://www.newsweek.com/bill-clinton-backpedals-monica-lewinsky-remarks-says-he-supports-metoo-959426",
"urlToImage": "http://s.newsweek.com/sites/www.newsweek.com/files/styles/full/public/2018/06/05/bill-clinton.jpg",
"publishedAt": "2018-06-05T16:15:00Z"
},
{
"source": {
"id": "cnn",
"name": "CNN"
},
"author": "Kevin Liptak, CNN",
"title": "Putin says he and Trump speak 'regularly.' Here's how often that is.",
"description": "Russian President Vladimir Putin said Tuesday he speaks \"regularly\" with President Donald Trump.",
"url": "https://www.cnn.com/2018/06/05/politics/trump-putin-obama-phone-calls/index.html",
"urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/170723124529-putin-trump-split-0723-super-tease.jpg",
"publishedAt": "2018-06-05T16:15:00Z"
},
{
"source": {
"id": null,
"name": "Latimes.com"
},
"author": "Associated Press",
"title": "Only a few of Guatemala volcano's dead have been identified",
"description": "Guatemalan authorities put the death toll at 69, but officials said just 17 had been identified so far because the intense heat of the volcanic debris flows left most bodies unrecognizable.",
"url": "http://www.latimes.com/world/la-fg-guatemala-volcano-20180605-story.html",
"urlToImage": "http://www.latimes.com/resizer/FbXh2zEF9Xm-uOiMCjQzve_4AQ0=/1200x0/www.trbimg.com/img-5b16ab3a/turbine/la-fg-guatemala-volcano-20180605",
"publishedAt": "2018-06-05T15:32:55Z"
},
{
"source": {
"id": "newsweek",
"name": "Newsweek"
},
"author": "Jason Lemon",
"title": "Crocodile Jumped Out Of Water And Killed Ethiopian Pastor During Baptism",
"description": "Fishermen and members of the congregation did their best to help Docho Eshete, a Protestant pastor.",
"url": "http://www.newsweek.com/crocodile-kills-pastor-baptism-ethiopia-959325",
"urlToImage": "http://s.newsweek.com/sites/www.newsweek.com/files/styles/full/public/2018/06/05/gettyimages-481847798.jpg",
"publishedAt": "2018-06-05T15:14:00Z"
},
{
"source": {
"id": "business-insider",
"name": "Business Insider"
},
"author": "John Haltiwanger",
"title": "Police swarmed the home of high school shooting survivor and gun safety advocate David Hogg after prank phone call",
"description": "The home of David Hogg, a survivor of the shooting at Marjory Stoneman Douglas High School, was \"swatted\" on Tuesday after a prank phone call told law enforcement there was a hostage situation at the residence.",
"url": "http://www.businessinsider.com/home-of-gun-safety-activist-david-hogg-swatted-after-prank-call-2018-6",
"urlToImage": "http://static.businessinsider.com/image/5b16a7e81ae66255008b4890-750.jpg",
"publishedAt": "2018-06-05T15:11:04Z"
},
{
"source": {
"id": "the-wall-street-journal",
"name": "The Wall Street Journal"
},
"author": "Lingling Wei",
"title": "China Offers to Buy Nearly $70 Billion of US Products to Fend Off Trade Tariffs",
"description": "China offered to purchase nearly $70 billion of U.S. farm and energy products if the Trump administration abandons threatened tariffs, according to people briefed on the latest negotiations with American trade officials.",
"url": "https://www.wsj.com/articles/china-offers-to-buy-nearly-70-billion-of-u-s-farm-and-energy-products-1528208835",
"urlToImage": "https://si.wsj.net/public/resources/images/B3-AR363_CHINAU_SOC_20180605101801.jpg",
"publishedAt": "2018-06-05T15:02:00Z"
},
{
"source": {
"id": "the-washington-post",
"name": "The Washington Post"
},
"author": null,
"title": "Actually, Melania, your disappearance is a legitimate news story",
"description": "The first lady’s office calls the news media ‘rabid’ for wondering why she has dropped out of sight.",
"url": "https://www.washingtonpost.com/lifestyle/style/actually-melania-your-disappearance-is-a-legitimate-news-story/2018/06/05/99294790-6813-11e8-9e38-24e693b38637_story.html",
"urlToImage": "https://www.washingtonpost.com/resizer/nNEjVK-l32KhAFz0TwAxab3sCYI=/1484x0/arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/GDRD6ODIKAI6RHRYETTJHM4GG4.jpg",
"publishedAt": "2018-06-05T14:56:58Z"
},
{
"source": {
"id": "the-washington-post",
"name": "The Washington Post"
},
"author": null,
"title": "I saw what Maria did to Puerto Rico's hospitals. The death toll is no surprise.",
"description": "Medical care, like everything else on the island, was virtually shut down after the storm.",
"url": "https://www.washingtonpost.com/news/posteverything/wp/2018/06/05/i-saw-what-maria-did-to-puerto-ricos-hospitals-the-death-toll-is-no-surprise/",
"urlToImage": "https://www.washingtonpost.com/resizer/cJ_w2hZJoT_niJfT-Lxfa4U5Yx0=/1484x0/arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/TM73JYEI2U36JHWOE5XHRJPLH4.jpg",
"publishedAt": "2018-06-05T14:36:24Z"
},
{
"source": {
"id": null,
"name": "Startribune.com"
},
"author": "Paul Walsh",
"title": "W. Minnesota woman's obit takes dark turn over long-ago extra-marital affair",
"description": "\"She will not be missed,\" said brief notice that grabbed international attention.",
"url": "http://www.startribune.com/w-minnesota-woman-s-obit-takes-dark-turn-over-long-ago-extra-marital-affair/484588991/",
"urlToImage": "http://stmedia.stimg.co/KATHLEEN+OBIT.JPG?h=630&w=1200&fit=crop&bg=999&crop=faces",
"publishedAt": "2018-06-05T14:32:35Z"
},
{
"source": {
"id": "the-new-york-times",
"name": "The New York Times"
},
"author": "Adam Nagourney",
"title": "California Primary Election Live Updates: Democrats Play for GOP-Held Seats",
"description": "This is a big Election Day in California, and the country is watching.",
"url": "https://www.nytimes.com/2018/06/05/us/politics/california-primary-elections-live.html",
"urlToImage": "https://static01.nyt.com/images/2018/06/06/us/06cal-briefing01sub/06cal-briefing01sub-facebookJumbo.jpg",
"publishedAt": "2018-06-05T14:19:30Z"
},
{
"source": {
"id": "the-washington-post",
"name": "The Washington Post"
},
"author": "https://www.facebook.com/jhohmann",
"title": "David Koch is leaving Koch Industries, stepping down from Americans for Prosperity",
"description": "His departure will change the makeup of one of the most active and well-funded political forces in the country that has been a bulwark in supporting Republicans.",
"url": "https://www.washingtonpost.com/news/powerpost/wp/2018/06/05/david-koch-is-leaving-koch-industries-stepping-down-from-americans-for-prosperity/",
"urlToImage": "https://www.washingtonpost.com/resizer/8_T_AplMQkWlnCKY1YjV5ZUcTpM=/1484x0/arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/NLFV5JNECY5THCNBBHUHUBCWJI.jpg",
"publishedAt": "2018-06-05T13:52:25Z"
},
{
"source": {
"id": null,
"name": "Cnet.com"
},
"author": "Jessica Dolcourt",
"title": "iOS 12: Siri Shortcuts, group FaceTime and 'Memoji' Animoji of you",
"description": "Everything Apple announced for the iPhone and iPad.",
"url": "https://www.cnet.com/how-to/ios-12-siri-group-facetime-memoji-and-more/",
"urlToImage": "https://cnet4.cbsistatic.com/img/3R5HtavVDjD49BYit44jLYHx2TQ=/670x503/2018/06/04/b5fcbc71-cc14-4997-8d6b-258849f7c955/2018-06-04-10-55-39.jpg",
"publishedAt": "2018-06-05T13:09:11Z"
},
{
"source": {
"id": null,
"name": "Charlotteobserver.com"
},
"author": "Ron Gallagher",
"title": "FBI joins search for baby as focus shifts to eastern NC for girl abducted by sex offender",
"description": "The case of Emma Grace Kennedy, a 7-month-old girl abducted Sunday from Virginia, took a strange twist Tuesday when police suspected a man reportedly trying to sell a baby in Durham, NC, might have been Carl Ray Kennedy, a convicted sex offender who police sa…",
"url": "http://www.charlotteobserver.com/latest-news/article212475059.html",
"urlToImage": "http://www.charlotteobserver.com/latest-news/yex0df/picture212552209/alternates/LANDSCAPE_1140/grace.png",
"publishedAt": "2018-06-05T12:48:40Z"
},
{
"source": {
"id": "usa-today",
"name": "USA Today"
},
"author": "Erin Jensen",
"title": "Miss America axes swimsuit competition; Gretchen Carlson says 'We are no longer a pageant'",
"description": "Gretchen Carlson, Miss America Organization Board of Trustees Chair, had a major announcement on Tuesday's \"Good Morning America\": There will be no more swimsuit competition going forward.",
"url": "https://www.usatoday.com/story/life/tv/2018/06/05/miss-america-swimsuit-competition-gretchen-carlson/672148002/",
"urlToImage": "https://www.gannett-cdn.com/-mm-/d2d65a8ee91f20a09714e3a6a6550e1c79d7cc4a/c=0-593-2143-1804&r=x1683&c=3200x1680/local/-/media/2018/06/05/USATODAY/USATODAY/636637819845616797-GTY-954664126-99625691.JPG",
"publishedAt": "2018-06-05T12:23:00Z"
},
{
"source": {
"id": "the-washington-post",
"name": "The Washington Post"
},
"author": "https://www.facebook.com/TomJackmanWP/",
"title": "Did LA police and prosecutors bungle the Bobby Kennedy assassination probe?",
"description": "Critics believe the police and prosecutors ignored evidence of two gunmen and pinned the case on Sirhan, leading Kathleen Kennedy Townsend to join calls for a new investigation.",
"url": "https://www.washingtonpost.com/news/true-crime/wp/2018/06/05/did-l-a-police-and-prosecutors-bungle-the-bobby-kennedy-assassination/",
"urlToImage": "https://www.washingtonpost.com/resizer/pOEENliV3eaP6uNcu5Ya1xq17D0=/1484x0/arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/RA4727Y34Q4WVDJNYH47G3QEIM.JPG",
"publishedAt": "2018-06-05T09:07:18Z"
},
{
"source": {
"id": null,
"name": "Npr.org"
},
"author": "",
"title": "In Narrow Opinion, Supreme Court Rules For Baker In Gay Rights Case",
"description": "The Supreme Court on Monday ruled that a local baker in Colorado was within his rights to refuse to bake a cake for a same-sex couple's wedding, but it did not go beyond this case.",
"url": "https://www.npr.org/2018/06/04/605003519/supreme-court-decides-in-favor-of-baker-over-same-sex-couple-in-cake-shop-case",
"urlToImage": "https://media.npr.org/assets/img/2018/06/04/ap_17312739950081_wide-bec75df27909bee8722ae7c351074cc1e1157801.jpg?s=1400",
"publishedAt": "2018-06-05T01:22:31Z"
}
]
}
And My Php code is decoding this data to an array and then after that, I couldn't separate the objects and arrays. I know how much results i have and i can simply loop through it but i need to know how do i get that data .
<?php
$json = file_get_contents('https://newsapi.org/v2/top-headlines?country=us&apiKey=5d0d49e595dc4b64a2fd3916b617ad8c');
print_r( json_decode($json, true));
$jsons= ( json_decode($json, true));
echo $jsons[0]["article"];
?>
Your PHP code is wrong, echo $jsons[0]["article"];. - This will not work.
You need to replace it with print_r( $jsons["articles"][0] );. Therefore, I think what you mean by JSON DATA is how you roll it out or going through the data.
Because you have set the assoc parameter to true, json_decode() will return an array.
First a correction to your code that hopefully help you to understand how json and array() works.
$json = file_get_contents('https://newsapi.org/v2/top-headlines?country=us&apiKey=5d0d49e595dc4b64a2fd3916b617ad8c');
print_r( json_decode($json, true));
$jsons= ( json_decode($json, true));
print_r( $jsons["articles"][0] );
echo $jsons["articles"][0]['title'];
In this example we will roll out all articles.
$json = file_get_contents('https://newsapi.org/v2/top-headlines?country=us&apiKey=5d0d49e595dc4b64a2fd3916b617ad8c');
$news = json_decode($json, true);
foreach ($news["articles"] as $i => $article) {
echo '<h2>' . $article['title'] . '</h2>';
echo '<img src="' . $article['urlToImage'] . '"/>';
echo '<p>Published on ' . $article['publishedAt'] . '</p>';
echo '<p>' . $article['description'] . '</p>';
echo 'Read more';
}
You may also want to see array() at w3schools.com.
$jsons is not an array, but an object. What you want is $jsons->articles[0].

Google Books API Limit Results

Is there any way to limit the results returned by the Google Books API?
For example the following URL:
https://www.googleapis.com/books/v1/volumes?q=isbn:0751538310
Returns the following:
"kind": "books#volumes",
"totalItems": 1,
"items": [
{
"kind": "books#volume",
"id": "ofTsHAAACAAJ",
"etag": "K6a+5IuCMD0",
"selfLink": "https://www.googleapis.com/books/v1/volumes/ofTsHAAACAAJ",
"volumeInfo": {
"title": "Panic",
"authors": [
"Jeff Abbott"
],
"publisher": "Grand Central Publishing",
"publishedDate": "2006",
"description": "Things are going well for young film-maker Evan Casher - until he receives an urgent phonecall from his mother, summoning him home. He arrives to find her brutally murdered body on the kitchen floor and a hitman lying in wait for him. It is then he realises his whole life has been a lie. His parents are not who he thought they were, his girlfriend is not who he thought she was, his entire existence an ingeniously constructed sham. And now that he knows it, he is in terrible danger. So he is catapulted into a violent world of mercenaries, spies and terrorists. Pursued by a ruthless band of killers who will stop at nothing to keep old secrets buried, Evan's only hope for survival is to discover the truth behind his past. An absolute page-turner, Panic has been acclaimed as one of the most exciting thrillers of recent years.",
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "0751538310"
},
{
"type": "ISBN_13",
"identifier": "9780751538311"
}
],
"readingModes": {
"text": false,
"image": false
},
"pageCount": 408,
"printType": "BOOK",
"categories": [
"Austin (Tex.)"
],
"maturityRating": "NOT_MATURE",
"allowAnonLogging": false,
"contentVersion": "preview-1.0.0",
"imageLinks": {
"smallThumbnail": "http://books.google.com/books/content?id=ofTsHAAACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api",
"thumbnail": "http://books.google.com/books/content?id=ofTsHAAACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"
},
"language": "en",
"previewLink": "http://books.google.co.uk/books?id=ofTsHAAACAAJ&dq=isbn:0751538310&hl=&cd=1&source=gbs_api",
"infoLink": "http://books.google.co.uk/books?id=ofTsHAAACAAJ&dq=isbn:0751538310&hl=&source=gbs_api",
"canonicalVolumeLink": "https://books.google.com/books/about/Panic.html?hl=&id=ofTsHAAACAAJ"
},
"saleInfo": {
"country": "GB",
"saleability": "NOT_FOR_SALE",
"isEbook": false
},
"accessInfo": {
"country": "GB",
"viewability": "NO_PAGES",
"embeddable": false,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": false
},
"pdf": {
"isAvailable": false
},
"webReaderLink": "http://books.google.co.uk/books/reader?id=ofTsHAAACAAJ&hl=&printsec=frontcover&output=reader&source=gbs_api",
"accessViewStatus": "NONE",
"quoteSharingAllowed": false
},
"searchInfo": {
"textSnippet": "An absolute page-turner, Panic has been acclaimed as one of the most exciting thrillers of recent years."
}
}
]
Is there any way I can return only the title and description? I think it may improve performance of my web application.
I have looked at the partial response but it doesn't seem to work.
I am including my API key in the URL query parameter.
Thanks
I added the params according to the partial response documentation.
See the params in following link:
https://www.googleapis.com/books/v1/volumes?q=isbn:0751538310&fields=items(volumeInfo/description,volumeInfo/title)
It will return:
{
"items": [
{
"volumeInfo": {
"title": "Panic",
"description": "Things are going well for young film-maker Evan Casher - until he receives an urgent phonecall from his mother, summoning him home. He arrives to find her brutally murdered body on the kitchen floor and a hitman lying in wait for him. It is then he realises his whole life has been a lie. His parents are not who he thought they were, his girlfriend is not who he thought she was, his entire existence an ingeniously constructed sham. And now that he knows it, he is in terrible danger. So he is catapulted into a violent world of mercenaries, spies and terrorists. Pursued by a ruthless band of killers who will stop at nothing to keep old secrets buried, Evan's only hope for survival is to discover the truth behind his past. An absolute page-turner, Panic has been acclaimed as one of the most exciting thrillers of recent years."
}
}
]
}
maxResults
include this in your query. 5 is just an integer.
&maxResults=5
Google will help you create your API with this website API called try it.
https://developers.google.com/books/docs/v1/reference/volumes/list?apix=true#try-it
Maybe its too late to respond but you need to activate the API before accessing it. When you try to access it says to activate it from console with some project id. Just copy that url and it takes you straight to your dashboard where you can find your activation button post which you can access the partial response with desired attributes.

How can I retrieve information from Json data in a format where almost everything is stored as an array?

I'm currently using a spider to crawl through reddit and provide me with links and titles in json format. However, when the json file is created the data is stored as individual arrays as shown here:
[{"url": ["http://i.imgur.com/1Pw3ehZ.jpg"], "title": ["Sunset in Trinidad, CA", "bungholesex"]},
{"url": ["http://i.imgur.com/neQiFcf.jpg"], "title": ["Humboldt Bay, Eureka California", "bungholesex"]},
{"url": ["http://imgur.com/dxKHGLV"], "title": ["Crater Lake, Oregon in April", "CausticRain11"]},
{"url": ["http://imgur.com/RPv475F"], "title": ["South Dakota is seriously beautiful.", "ratt1601"]},
{"url": ["http://imgur.com/oH1u7nk"], "title": ["The view outside my back door. Virginia is alright, I guess...", "toowhitetofail"]},
Whenever I go to retrieve and echo the data converted with json_decoder I receive a notice saying "array to string conversion" but there is no data shown.
Try this code:
$data = '[{"url": ["http://i.imgur.com/1Pw3ehZ.jpg"], "title": ["Sunset in Trinidad, CA", "bungholesex"]},
{"url": ["http://i.imgur.com/neQiFcf.jpg"], "title": ["Humboldt Bay, Eureka California", "bungholesex"]},
{"url": ["http://imgur.com/dxKHGLV"], "title": ["Crater Lake, Oregon in April", "CausticRain11"]},
{"url": ["http://imgur.com/RPv475F"], "title": ["South Dakota is seriously beautiful.", "ratt1601"]},
{"url": ["http://imgur.com/oH1u7nk"], "title": ["The view outside my back door. Virginia is alright, I guess...", "toowhitetofail"]}]';
$array = json_decode($data, true);
foreach ($array as &$item) {
$item['url'] = $item['url'][0];
$item['title'] = implode(', ', $item['title']);
}
echo json_encode($array);
I am using first array item of url because it is always single in your example. And it makes no sense to concatenate urls - resut will not be valid url. But if you want, urls can be concatenated same way as title.
Result will look like this:
[
{
"url": "http://i.imgur.com/1Pw3ehZ.jpg",
"title": "Sunset in Trinidad, CA, bungholesex"
},
{
"url": "http://i.imgur.com/neQiFcf.jpg",
"title": "Humboldt Bay, Eureka California, bungholesex"
},
{
"url": "http://imgur.com/dxKHGLV",
"title": "Crater Lake, Oregon in April, CausticRain11"
},
{
"url": "http://imgur.com/RPv475F",
"title": "South Dakota is seriously beautiful., ratt1601"
},
{
"url": "http://imgur.com/oH1u7nk",
"title": "The view outside my back door. Virginia is alright, I guess..., toowhitetofail"
}
]
You can check it here.
Your Json above not valid. u should remove , and add ] at the end of your json.
U can check it using json validaor here.
http://jsonlint.com/
[{
"url": ["http://i.imgur.com/1Pw3ehZ.jpg"],
"title": ["Sunset in Trinidad, CA", "bungholesex"]
}, {
"url": ["http://i.imgur.com/neQiFcf.jpg"],
"title": ["Humboldt Bay, Eureka California", "bungholesex"]
}, {
"url": ["http://imgur.com/dxKHGLV"],
"title": ["Crater Lake, Oregon in April", "CausticRain11"]
}, {
"url": ["http://imgur.com/RPv475F"],
"title": ["South Dakota is seriously beautiful.", "ratt1601"]
}, {
"url": ["http://imgur.com/oH1u7nk"],
"title": ["The view outside my back door. Virginia is alright, I guess...", "toowhitetofail"]
}]

Loop through JSON from jquery getJSON

Here is the code:
$.getJSON( base_url + '/ajax/sortListings.php', { sort: sort }, function( data ) {
$.each(data, function(i, json) {
$( '#listings' ).append($('<div>').load( base_url + '/partialviews/listingAdminPrev.php', {
id: json.id,
name: json.name,
logo: encodeURIComponent(json.logo),
address: json.address,
city: json.city,
state: json.state,
zip: json.zip,
phone: json.phone,
email: json.email,
web_link: encodeURIComponent(json.web_link),
services: json.services,
category: json.category,
status: json.status,
created: json.created
} ));
});
});
When I manually go to the sortListings.php file and turn the $_POST variables to $_GET, it works fine. So nothing is wrong with the file. But here it is anyway:
include_once('../../app/scripts/config.php');
$listingObject = Listing::getInstance();
$results = $listingObject->get_listings($_POST['sort']);
echo json_encode($results);
That file returns this:
[
{
"id": "32",
"user_id": "32",
"logo": "32_52a0960ba791c.jpg",
"name": "Anthony Thomas Advertising",
"address": "380 S. Main St.",
"city": "Akron",
"state": "AL",
"zip": "44311",
"phone": "3302536888",
"email": "wayne#anthonythomas.com",
"web_link": "http://www.aol.com",
"status": "1",
"services": "dfhfdhdfh",
"category": "1",
"created": "2013-12-05 09:32:56"
},
{
"id": "20",
"user_id": "10",
"logo": "10_529f96001390d.png",
"name": "Graphic Installation Services",
"address": "2808 Broadway Blvd Unit 1",
"city": "Monroeville",
"state": "PA",
"zip": "15146",
"phone": "3306599898",
"email": "graphic#graphicinstallationservices.com",
"web_link": "",
"status": "4",
"services": "Graphic installation services",
"category": "1",
"created": "2013-12-04 11:35:11"
},
{
"id": "21",
"user_id": "10",
"logo": "10_529f9c1a8375d.png",
"name": "Intellect Productions",
"address": "2915 13th St NW",
"city": "Canton",
"state": "OH",
"zip": "44708",
"phone": "3309334833",
"email": "mouseywings#live.com",
"web_link": "",
"status": "1",
"services": "Car Wrap Installations by Intellect Productions",
"category": "1",
"created": "2013-12-04 15:20:15"
},
{
"id": "19",
"user_id": "10",
"logo": "10_529cf170b08d7.png",
"name": "International Installations Inc",
"address": "833 Wooster Rd N",
"city": "Barberton",
"state": "OH",
"zip": "44203",
"phone": "3306586526",
"email": "internationalinstallers#internationinstallers.com",
"web_link": "http://intellectproductions.com/",
"status": "1",
"services": "We install:\r\n· vehicle wraps\r\n· decals\r\n· vehicle lettering\r\n· banners\r\n· billboards\r\n· murals\r\nInternational Image Application Inc. is PDAA certified. We strive to deliver a constant flow of high quality work using best materials in the business, and unsurpassed skill. This ensures that our clients receive value for money, and more bang for their buck!\r\nAnd to ensure that our clients continue to receive the highest quality of work possible, we stay on top of technological trends, new materials, and installation techniques. This dedication to continued education has resulted in many clients coming back again and again.\r\nFrom a simple vehicle wraps installation to an entire ad campaign or fleet, International Image Application Inc. is your destination for precision graphics installation on virtually any medium.",
"category": "1",
"created": "2013-12-04 10:32:52"
}
]
Which is 5 listings.. so it's pulling the data fine. However, nothing is working beyond the $.each().. I even tried alerting stuff and nothing.
No console errors are thrown either..
You hit on your problem. You are expecting the sort parameter in $_POST while you are calling getJSON() which executes a GET.
Make up your mind whether you want to use GET or POST and be consistent.
My guess is you also need to put better error handling in Listing::get_listings() method to provide useful errors when you are not getting the data your expect passed to it.

How to loop through JSON array using PHP

My PHP code:
$obj = json_decode($data);
print $obj->{'name'};
While it works for non-arrays, I can't for the life of me figure out how to print all the values within the "Reviews" Array.
What I would like to do is to loop through this response, probably with forreach(), resulting in a list containing the rating and excerpt for each review in the response.
Any guidance / direction is greatly appreciated..
Below is the JSON I'm working with. (it is the response from the Yelp API).
{
"is_claimed": true,
"rating": 4.5,
"mobile_url": "http://m.yelp.com/biz/economy-paint-and-collision-riverside",
"rating_img_url": "http://s3-media2.ak.yelpcdn.com/assets/2/www/img/99493c12711e/ico/stars/v1/stars_4_half.png",
"review_count": 19,
"name": "Economy Paint & Collision",
"snippet_image_url": "http://s3-media3.ak.yelpcdn.com/photo/ZOzoahw0Go_DEPLvxCaP_Q/ms.jpg",
"rating_img_url_small": "http://s3-media2.ak.yelpcdn.com/assets/2/www/img/a5221e66bc70/ico/stars/v1/stars_small_4_half.png",
"url": "http://www.yelp.com/biz/economy-paint-and-collision-riverside",
"reviews": [
{
"rating": 3,
"excerpt": "The Good:\nDennis quoted me a price over the phone about 1 month before I took my wifes 2010 Escalade in for repairs and when I took it in he gave me the...",
"time_created": 1357010247,
"rating_image_url": "http://s3-media3.ak.yelpcdn.com/assets/2/www/img/34bc8086841c/ico/stars/v1/stars_3.png",
"rating_image_small_url": "http://s3-media3.ak.yelpcdn.com/assets/2/www/img/902abeed0983/ico/stars/v1/stars_small_3.png",
"user": {
"image_url": "http://s3-media3.ak.yelpcdn.com/photo/mIsU7ugYd88lLA-XL2q1Cg/ms.jpg",
"id": "V9MDZvEBv-tBTF4YIoc7mg",
"name": "Sydney H."
},
"rating_image_large_url": "http://s3-media1.ak.yelpcdn.com/assets/2/www/img/e8b5b79d37ed/ico/stars/v1/stars_large_3.png",
"id": "HfOhzLIlJoUKSKU8euclqA"
},
{
"rating": 5,
"excerpt": "Dennis and his team did an amazing job on the roof of my fiancee's 2002 Acura RSX after years of living by the beach in San Francisco had mostly rusted...",
"time_created": 1354741952,
"rating_image_url": "http://s3-media1.ak.yelpcdn.com/assets/2/www/img/f1def11e4e79/ico/stars/v1/stars_5.png",
"rating_image_small_url": "http://s3-media1.ak.yelpcdn.com/assets/2/www/img/c7623205d5cd/ico/stars/v1/stars_small_5.png",
"user": {
"image_url": "http://s3-media3.ak.yelpcdn.com/photo/ZOzoahw0Go_DEPLvxCaP_Q/ms.jpg",
"id": "kOqCnCjYn0EbAhtH1tfjcw",
"name": "Jason H."
},
"rating_image_large_url": "http://s3-media3.ak.yelpcdn.com/assets/2/www/img/22affc4e6c38/ico/stars/v1/stars_large_5.png",
"id": "YzZg1LX6zeRaurq9tYUcMw"
},
{
"rating": 5,
"excerpt": "It's been a year since I had my car painted here, and I gotta say: It still looks just as good as it did when I first picked it up. You would never know...",
"time_created": 1361043626,
"rating_image_url": "http://s3-media1.ak.yelpcdn.com/assets/2/www/img/f1def11e4e79/ico/stars/v1/stars_5.png",
"rating_image_small_url": "http://s3-media1.ak.yelpcdn.com/assets/2/www/img/c7623205d5cd/ico/stars/v1/stars_small_5.png",
"user": {
"image_url": "http://s3-media1.ak.yelpcdn.com/photo/58coTtu1x5riHSgFEAQsfw/ms.jpg",
"id": "kVrW3138d5VL-AZ97wFF4A",
"name": "Jeanne M."
},
"rating_image_large_url": "http://s3-media3.ak.yelpcdn.com/assets/2/www/img/22affc4e6c38/ico/stars/v1/stars_large_5.png",
"id": "r5WtlQVMXiIMBR6S3N7RZw"
}
],
"phone": "9517870227",
"snippet_text": "Dennis and his team did an amazing job on the roof of my fiancee's 2002 Acura RSX after years of living by the beach in San Francisco had mostly rusted...",
"image_url": "http://s3-media3.ak.yelpcdn.com/bphoto/kodoEcmgHRG61pPaWRndbw/ms.jpg",
"categories": [
[
"Body Shops",
"bodyshops"
],
[
"Auto Repair",
"autorepair"
]
],
"display_phone": "+1-951-787-0227",
"rating_img_url_large": "http://s3-media4.ak.yelpcdn.com/assets/2/www/img/9f83790ff7f6/ico/stars/v1/stars_large_4_half.png",
"id": "economy-paint-and-collision-riverside",
"is_closed": false,
"location": {
"city": "Riverside",
"display_address": [
"2548 Rubidoux Blvd",
"Riverside, CA 92509"
],
"geo_accuracy": 8,
"postal_code": "92509",
"country_code": "US",
"address": [
"2548 Rubidoux Blvd"
],
"coordinate": {
"latitude": 34.0132437,
"longitude": -117.3923804
},
"state_code": "CA"
}
}
You are probably having trouble because reviews is an array and you are trying to access it as a JSON object.
$obj = json_decode($data, TRUE);
for($i=0; $i<count($obj['reviews']); $i++) {
echo "Rating is " . $obj['reviews'][$i]["rating"] . " and the excerpt is " . $obj['reviews'][$i]["excerpt"] . "<BR>";
}
I'm not sure what exactly you want but I guess you want print it just for debugging right now. You can try with print_r($obj); and var_dump($obj); - they must print something, especially var_dump().
When you see the data, you can easily edit function a little bit, so you can do for instance print_r($obj->reviews) or print_r($obj['reviews']), depending if $obj is object or array.
You can use var_dump or print_r.
<?php
$decodedJSON = json_decode($jsonData);
// Put everyting to the screen with var_dump;
var_dump($decodedJSON);
// With print_r ( useful for arrays );
print_r($decodedJSON);
// List just review ratings with foreach;
foreach($decodedJSON['reviews'] as $review){
echo $review['rating'];
}
?>
Here using objects example (to read reviews...raiting):
$jsonObject = json_decode($data);
foreach ($jsonObject->reviews as $data) {
echo $data->rating;
}

Categories