I'm attempting to pull in data from Google's Shopping API. I'm able to download the data successfully, but I'm having trouble parsing through it with PHP. I'm still learning, but I seem to be having issues with multi-dimensional arrays. I capture the JSON with $json = json_decode($data);.
The following just echos the outer array, but I can't pull from the inner array:
foreach($json as $key => $value) {
echo $key . " : " . $value;
}
If I want to grab the "title", "description", "brand", and "availability" for each product, how would I parse through it?
{
"kind": "shopping#products",
"etag": "\"T9uPnY2MZMB71TDpKXXZdr3yWX4/qtJ5vmpftFWNfijyLD9ti2Xpj-w\"",
"id": "tag:google.com,2010:shopping/products",
"selfLink": "https://www.googleapis.com/shopping/search/v1/public/products?country\u003dus&q\u003dsony&maxResults\u003d3&startIndex\u003d2",
"nextLink": "https://www.googleapis.com/shopping/search/v1/public/products?country\u003dus&q\u003dsony&maxResults\u003d3&startIndex\u003d5",
"previousLink": "https://www.googleapis.com/shopping/search/v1/public/products?country\u003dus&q\u003dsony&maxResults\u003d3&startIndex\u003d1",
"totalItems": 633694,
"startIndex": 2,
"itemsPerPage": 3,
"currentItemCount": 3,
"items": [
{
"kind": "shopping#product",
"id": "tag:google.com,2010:shopping/products/1161353/11882813508247586172",
"selfLink": "https://www.googleapis.com/shopping/search/v1/public/products/1161353/gid/11882813508247586172",
"product": {
"googleId": "11882813508247586172",
"author": {
"name": "Buy.com",
"accountId": "1161353"
},
"creationTime": "2011-04-24T05:13:38.000Z",
"modificationTime": "2011-08-05T17:45:24.000Z",
"country": "US",
"language": "en",
"title": "Sony BRAVIA KDL-46EX720 46 inch 3D LED HDTV 1080p 120Hz",
"description": "Entertainment lovers the slim Sony EX720-Series LED HDTV is for you. See precise motion detail plus watch your favorite 2D or 3D entertainment in clear, vivid Full HD 1080p picture quality with incredible contrast. You can even connect to the internet and access a great selection of online entertainment with Netflix , Hulu Plus , Pandora , Qriocity and more - there s always something on. Plus video chat with friends and family when you Skype on the big screen.",
"link": "http://clickfrom.buy.com/default.asp?adid\u003d17902&sURL\u003dhttp%3A%2F%2Fwww.buy.com%2Fprod%2Fsony-bravia-kdl-46ex720-46-3d-led-hdtv-1080p-120hz%2Fq%2Fsellerid%2F10004001%2Floc%2F111%2F219891693.html",
"brand": "Sony",
"condition": "new",
"gtin": "00027242817081",
"gtins": [
"00027242817081"
],
"inventories": [
{
"channel": "online",
"availability": "inStock",
"price": 1348.0,
"currency": "USD"
}
],
"images": [
{
"link": "http://ak.buy.com/PI/0/1000/219891693.jpg"
}
]
}
},
{
"kind": "shopping#product",
"id": "tag:google.com,2010:shopping/products/7827/1976288072671326122",
"selfLink": "https://www.googleapis.com/shopping/search/v1/public/products/7827/gid/1976288072671326122",
"product": {
"googleId": "1976288072671326122",
"author": {
"name": "Dell",
"accountId": "7827"
},
"creationTime": "2011-06-08T15:11:49.000Z",
"modificationTime": "2011-08-05T15:04:13.000Z",
"country": "US",
"language": "en",
"title": "Sony Bravia 55\" KDL55EX500 1080p 120Hz LCD HDTV",
"description": "Enjoy breathtaking viewing experience with Bravia 55-inch KDL55EX500 1080p LCD HDTV from Sony®. This LCD TV features Motionflow™ 120 Hz Technology that allows you to experience smooth motion detail and clarity which delivers a crisp, fluid and realistic viewing skill during fast-action scenes. Additionally, the incorporated LightSensor™ Technology automatically increases or decreases the level of brightness of your TV's backlight based on a room's lighting conditions. Moreover, the BRAVIA Engine™ 2 fully processor lets you enjoy sharp, vibrant, life-like images while optimizing color, contrast and significantly reducing noise. Besides this, get a natural looking picture with an Ambient Sensor. Plus, you can also share your photos and music on the big screen by simply connecting your digital camera, USB-enabled MP3 player, or USB storage device directly to your HDTV's USB input. With all these features loaded into a single television the Bravia EX500 is an ideal choice to complement your digital lifestyle.var wcCpi\u003d\"A3477150\";",
"link": "http://lt.dell.com/lt/lt.aspx?CID\u003d27530&LID\u003d627063&DGC\u003dSS&DGSeg\u003dDHS&DURL\u003dhttp://accessories.us.dell.com/sna/productdetail.aspx?c\u003dus%26l\u003den%26s\u003ddhs%26cs\u003d19%26sku\u003dA3477150%26CAWELAID\u003d469727188",
"brand": "Sony",
"condition": "new",
"gtin": "00027242784932",
"gtins": [
"00027242784932"
],
"inventories": [
{
"channel": "online",
"availability": "inStock",
"price": 1348.0,
"currency": "USD"
}
],
"images": [
{
"link": "http://accessories.us.dell.com/sna/images/products/large/A3477150temp.jpg"
}
]
}
},
{
"kind": "shopping#product",
"id": "tag:google.com,2010:shopping/products/1113342/9429326904502109794",
"selfLink": "https://www.googleapis.com/shopping/search/v1/public/products/1113342/gid/9429326904502109794",
"product": {
"googleId": "9429326904502109794",
"author": {
"name": "Walmart",
"accountId": "1113342"
},
"creationTime": "2011-03-26T23:58:51.000Z",
"modificationTime": "2011-08-04T19:42:49.000Z",
"country": "US",
"language": "en",
"title": "Sony Bravia 32\" Class 3D LED-LCD 1080p 240Hz HDTV,1.68\" ultra-Slim,",
"description": "Note: You must have a source of HD programming in order to take full advantage of the Sony Bravia 32\" Class 3D 1080p LED HDTV. Contact your local cable or satellite TV provider for details on how to upgrade.Visit the Sony Brand Shop for 3D glasses, other 3D HDTVs and more.Sony Bravia 32\" Class 3D 1080p LED HDTV 240Hz, KDL-32EX720:See It All In 3D: Engineered with advanced technologies, the EX720 Series is more than a fully-loaded HDTV with 3D. Once you slide on the active shutter glasses (sold separately), the on-screen image is precisely synchronized and delivered with the Full HD image intact for an immersive entertainment viewing experience with maximum resolution and superb clarity.Slim Design, Stunning Picture: Experience the next level of picture quality and contrast with Edge LED Backlight technology. U",
"link": "http://www.walmart.com/ip/Sony-KDL-32EX720/15780230?sourceid\u003d1500000000000003142050&ci_src\u003d14110944&ci_sku\u003d15780230",
"brand": "Sony",
"condition": "new",
"gtin": "00027242817135",
"gtins": [
"00027242817135"
],
"inventories": [
{
"channel": "online",
"availability": "inStock",
"price": 898.0,
"currency": "USD"
}
],
"images": [
{
"link": "http://i.walmartimages.com/i/p/00/02/72/42/81/0002724281713_500X500.jpg"
}
]
}
}
]
}
If I was you, I would parse the JSON as an array instead of as an object. This can be done by doing the following:
$json = json_decode($data, true);
By included the second argument in json_decode with a value of true, you get back an array. You can then do something like:
echo '<pre>';
print_r($json);
exit;
This will give you an idea of the array structure of the data and how to access the information you want. For example, to pull the title, brand, and description of each item, you'd do the following:
foreach($json['items'] as $item) {
echo 'Title: ' . $item['product']['title'] . '<br />';
echo 'Brand: ' . $item['product']['brand'] . '<br />';
echo 'Description: ' . $item['product']['description'] . '<br />';
}
To get the availability, again do a dump of the array using print_r() and figure out the best way to access it from the array.
Your JSON is a mix of arrays and objects. So array notation will not work for all items.
For example, to find the brand use:
foreach ($json->items as $item) {
var_dump($item->product->brand);
}
Codepad example
JSON specification
We can parse JSON Array like this,
<?php
$json = "[{\"name\":\"user1\",\"id\":\"940\"},{\"name\":\"user2\",\"id\":\"949\"}]";
$dec = json_decode($json);
for($idx = 0; $idx < count($dec); $idx++){
$obj = (Array)$dec[$idx];
echo $obj["name"];
}
?>
and similarly JSON Object like this,
<?php
$json = "{\"name\":\"user1\",\"id\":\"940\"}";
$dec = (Array)json_decode($json);
echo $dec["name"];
?>
You can use this json parser for seeing your content in proper format.
You can use this code:
$json = json_decode($url,true);
//you can retrieve kind, tag, id by using
$kind = $json['kind'];
$id = $json['id'];
Here, items itself will have an array that you can use this
$items[] = $json['items'];
// you can retrieve the data inside the kind array
$kind_arr = $json['items'][0][]['kind'];
//similarly you can parse all the data
This is not a JSON issue. You just need to traverse the arrays. A simple print_r($json); will show you the structure.
In your case you probably need:
foreach ($json["items"] as $item) {
foreach ($item["product"] as $key => $value) {
echo $key . " : " . $value;
}
}
The first foreach loops over the item list. And the second subarray access ["product"] will get you to the desired attributes.
$json = '{ "a1":{ "field1":"name1", "field2":age1, "field3":"country1"
},
"a2":{ "field1":"name2", "field2":age2, "field3":"country2" },
"a3":{ "field1":"name3", "field2":age3, "field3":"country3" } }';
$Array = json_decode($json, true);
foreach ($Array as $key => $value)
{
echo " $key ";
foreach ($value as $k => $val)
{
echo "$k | $val <br />";
}
}
Related
i'm trying to build a json array in php, but a more complex one.
The point is, that i'm trying to make a database for dish calculations, and the array should look something like that.
Each dish has a name, a base weight, diameter and height. It also has half-finished products that include a single product with its weight.
For example There's a finished product Called "Cake" they base weight is 750 g., the height is 8cm and the diameter is 8cm. Now this cake is made from 3 different half-products that build up the 750g.:
Dough (300 g.)
Icing (300 g.)
Decorations. (150 g.)
And now every half-product has its own single product that builds it up
Dough: 300g.
Flour 100g
Water 100 g
Something else 100g.
And so on for every half product.
I've tried building arrays but this one seems a bit to hard for me, any suggestions on how todo this? Thanks!
EDIT: I need to get something like this
[
{
"Title": "Cake",
"base_weight": 750,
"base_height": 8,
"base_diameter": 14,
"half_products": [
{
"title": "Dough",
"weight": 300,
"ingredients": [
{
"title": "Flour",
"Weight": 150
},
{
"title": "Water",
"Weight": 150
}
]
},
{
"title": "Icing",
"weight": 300,
"ingredients": [
{
"title": "Flour",
"Weight": 150
},
{
"title": "Water",
"Weight": 150
}
]
},
{
"title": "Decorations",
"weight": 150,
"ingredients": [
{
"title": "Flowers",
"Weight": 150
}
]
}
]
}
]
You can use recursive tree methods for it and then you can easily convert it to json.
Arnaud Le Blanc coded it before here
https://stackoverflow.com/a/4844073/2528471
function buildTree($items) {
$childs = array();
foreach($items as &$item)
$childs[(int)$item['parent_id']][] = &$item;
foreach($items as &$item)
if (isset($childs[$item['id']]))
$item['childs'] = $childs[$item['id']];
return $childs[0];
}
$tree = buildTree($items); // $items variable must store all data from your database table
You can use it and then use the standard php method easily.
json_encode($tree);
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;
}
Recently, our team is going to develop mobile(iphone, android platforms) applications for our existing website, let user can use the application to more easy to read our content via the application.
But our team have different views in JSON schema of the API return, below are the sample response.
Schema type 1:
{
"success": 1,
"response": {
"threads": [
{
"thread_id": 9999,
"title": "Topic haha",
"content": "blah blah blah",
"category": {
"category_id": 100,
"category_name": "Chat Room",
"category_permalink": "http://sample.com/category/100"
},
"user": {
"user_id": 1,
"name": "Hello World",
"email": "helloworld#hello.com",
"user_permalink": "http://sample.com/user/Hello_World"
},
"post_ts": "2012-12-01 18:16:00T0800"
},
{
"thread_id": 9998,
"title": "asdasdsad ",
"content": "dsfdsfdsfds dsfdsf ds",
"category": {
"category_id": 101,
"category_name": "Chat Room 2",
"category_permalink": "http://sample.com/category/101"
},
"user": {
"user_id": 2,
"name": "Hello baby",
"email": "hellobaby#hello.com",
"user_permalink": "http://sample.com/user/2"
},
"post_ts": "2012-12-01 18:15:00T0800"
}
]
}
}
Schema type 2:
{
"success": 1,
"response": {
"threads": [
{
"thread_id": 9999,
"title": "Topic haha",
"content": "blah blah blah",
"category": 100,
"user": 1,
"post_ts": "2012-12-01 18:16:00T0800"
},
{
"thread_id": 9998,
"title": "asdasdsad ",
"content": "dsfdsfdsfds dsfdsf ds",
"category": 101,
"user": 2,
"post_ts": "2012-12-01 18:15:00T0800"
}
],
"category": [
{
"category_id": 100,
"category_name": "Chat Room",
"category_permalink": "http://sample.com/category/100"
},
{
"category_id": 101,
"category_name": "Chat Room 2",
"category_permalink": "http://sample.com/category/101"
}
],
"user": [
{
"user_id": 1,
"name": "Hello World",
"email": "helloworld#hello.com",
"user_permalink": "http://sample.com/user/Hello_World"
},
{
"user_id": 2,
"name": "Hello baby",
"email": "hellobaby#hello.com",
"user_permalink": "http://sample.com/user/Hello_baby"
}
]
}
}
Some Developers claim that if using schema type 2,
can reduce data size if the category & user entities comes too much duplicated. it does really reduce at least 20~40% size of response plain text.
once if the data size come less, in parsing it to JSON object, the memory get less
categoey & user can be store in hash-map, easy to reuse
reduce the overhead on retrieving data
I have no idea on it if schema type 2 does really enhanced. Because I read so many API documentation, never seen this type of schema design. For me, it looks like a relational database. So I have few questions, because I have no experience on designing a web services API.
Does it against API design principle (Easy to read, Easy to use) ?
Does it really get faster and get less memory resource on parsing on IOS / Android platform?
Does it can reduce the overhead between client & server?
Thanks you.
When I do such an application for android, I parse JSON just one and put it in database. Later I'm using ContentProvider to access it. In Your case You could use 2nd schema but without user, category part. Use lazy loading instead but it will be good solution just in case categories and users repeat often.
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);
I'm running this in the URL:
https://www.googleapis.com/shopping/search/v1/public/products?key=thekey&country=US&q=xbox+360&alt=json
This gives me output like:
{
"kind": "shopping#products",
"etag": "\"czKOfew9E3svi7vOBQ3vsAgGZzo/s56qwZYTznZuaaCXzw1weX_JANI\"",
"id": "tag:google.com,2010:shopping/products",
"selfLink": "https://www.googleapis.com/shopping/search/v1/public/products?country=US&q=xbox+360&alt=json&startIndex=1&maxResults=25",
"nextLink": "https://www.googleapis.com/shopping/search/v1/public/products?country=US&q=xbox+360&alt=json&startIndex=26&maxResults=25",
"totalItems": 203461,
"startIndex": 1,
"itemsPerPage": 25,
"currentItemCount": 25,
"items": [
{
"kind": "shopping#product",
"id": "tag:google.com,2010:shopping/products/1113342/8881409096328278418",
"selfLink": "https://www.googleapis.com/shopping/search/v1/public/products/1113342/gid/8881409096328278418?alt=json",
"product": {
"googleId": "8881409096328278418",
"author": {
"name": "Walmart",
"accountId": "1113342"
},
"creationTime": "2011-11-13T21:18:07.000Z",
"modificationTime": "2011-12-08T01:12:50.000Z",
"country": "US",
"language": "en",
"title": "More Facts On Xbox 360 4gb Capabilities",
"description": "Xbox 360 4GB ConsoleBuilt-in Wi-Fi: The new Microsoft Xbox 360 console is the only console with 802.11n Wi-Fi built-in for a faster and easier connection to Xbox LIVE. Stream HD movies and TV or download games from Xbox LIVE in 1080p and 5.1 surround sound from anywhere in the house. Compatible with b/g/n networks.Xbox LIVE: Xbox LIVE brings a world of entertainment to you. Instantly watch movies and TV streaming from Netflix. In crystal-clear HD, or download game add-ons like new levels, characters, maps and songs. Easily jump right into online multiplayer fun and play along with friends around the world. Plus, get your favorite music from Last.fm, connect with friends on Facebook and post Tweets on Twitter. Xbox LIVE is your connection to more games, entertainment and fun.Kinect-Ready: Featuring a dedicated, specialized port, this Microsoft Xbox 360 console is built to connect seamlessly with the Kinect Sensor. Kin",
"link": "http://www.walmart.com/catalog/product.do?product_id=14917960&sourceid=1500000000000003142040&ci_src=14110944&ci_sku=14917960",
"brand": "Microsoft",
"condition": "new",
"gtin": "00885370138405",
"gtins": [
"00885370138405"
],
"inventories": [
{
"channel": "online",
"availability": "inStock",
"price": 199.0,
"shipping": 7.97,
"currency": "USD"
}
],
"images": [
{
"link": "http://i.walmartimages.com/i/p/00/88/53/70/13/0088537013840_500X500.jpg"
}
]
}
},
{
"kind": "shopping#product",
"id": "tag:google.com,2010:shopping/products/10046/10100715335711953213",
"selfLink": "https://www.googleapis.com/shopping/search/v1/public/products/10046/gid/10100715335711953213?alt=json",
"product": {
"googleId": "10100715335711953213",
"author": {
"name": "Target",
"accountId": "10046"
},
"creationTime": "2011-08-23T19:06:38.000Z",
"modificationTime": "2011-12-09T22:37:12.000Z",
"country": "US",
"language": "en",
"title": "Xbox 360 4gb Console",
"description": "The new Xbox 360 4GB Console. Here today, ready for tomorrow with a brand new, leaner machine. Wi-Fi is built-in for easier connection to the world of entertainment on Xbox LIVE, where HD movies and TV stream in an instant. It s ready for the controller-free experiences of Kinect you don t just play the game, you are the game. Xbox 360 is more games, entertainment and fun. What s In The Box? Xbox 360 4GB S Console Xbox 360 Black Wireless Controller Xbox 360 Composite A/V cable (standard definition) One Month Xbox LIVE Gold Membership 1 year limited warranty on console",
"link": "http://www.target.com/p/Xbox-360-4GB-Console/-/A-12885804?ref=tgt_adv_XSG10001&AFID=Froogle_df&LNM=%7C12885804&CPNG=video%20games&ci_src=14110944&ci_sku=12885804",
"brand": "Microsoft",
"condition": "new",
"gtin": "00885370138405",
"gtins": [
"00885370138405"
],
"inventories": [
{
"channel": "online",
"availability": "inStock",
"price": 199.99,
"shipping": 12.85,
"currency": "USD"
}
],
"images": [
{
"link": "http://img3.targetimg3.com/wcsstore/TargetSAS/img/p/12/88/12885804.jpg"
}
]
}
},
{
"kind": "shopping#product",
"id": "tag:google.com,2010:shopping/products/1161353/4408757490534070643",
"selfLink": "https://www.googleapis.com/shopping/search/v1/public/products/1161353/gid/4408757490534070643?alt=json",
"product": {
"googleId": "4408757490534070643",
"author": {
"name": "Buy.com",
"accountId": "1161353"
},
"creationTime": "2011-04-24T04:06:32.000Z",
"modificationTime": "2011-12-09T06:24:51.000Z",
"country": "US",
"language": "en",
"title": "Xbox 360 System (4GB)",
"description": "Product Description The new Xbox 360. Here today, ready for tomorrow with a brand new, leaner machine in an all new black gloss finish. Wi-Fi is built-in for easier connection to the world of entertainment on Xbox LIVE, where HD movies and TV stream in an instant. Kinect Ready Featuring a dedicated, specialized port, the Xbox 360 4GB is built to connect seamlessly with the Kinect Sensor. Kinect brings games and entertainment to life in extraordinary new ways no controller required. Easy to use and instantly fun, Kinect gets everyone off the couch moving, laughing and cheering. See a ball? Kick it. Want to join a friend in the fun? Simply jump in. Even control an HD movie with a wave of your hand. Xbox LIVE Xbox LIVE brings a world of entertainment to you. Instantly watch movies and TV streaming from Netflix. In crystal-clear HD, or download game add-ons like new levels, characters, maps and songs. Easily jump right into online multiplayer fun and play along with friends around the world. Plus, get your favorite music from Last.fm and your Zune Pass, connect with friends on Facebook and post Tweets on Twitter. Xbox LIVE is your connection to more games, entertainment and fun. Looking for more than just a video game system? Just connect your Digital Camera, iPod, Zune, or other MP3 player via USB cable and immediately begin enjoying all your favorite Music and Movies on the TV that your Xbox 360 is hooked up to. It plays DVDs and CDs and you can even download the latest movies and TV shows via Xbox Live. It is a full Windows Media Extender and can connect with other PCs around the house to stream your favorite media. What Does Xbox Live Mean or Do? Join Xbox Live to have full access to the Marketplace where you can download full Games, Demos, Trailers, Movies and more. Voice, Text, and Video chat with friends and even play games together online (Note: multiplayer gaming requires Xbox Live Gold subscription). Xbox 360 Games To Watch Out For Gears of War 3 Call of Duty: Modern Warfare 3 Assassin's Creed: Revelations Tomb Raider Battlefield 3 Deus Ex: Human Revolution Child of Eden Xbox 360 Wireless Controller (black) This award-winning, high-performance wireless controller features a range of up to 30 feet and a battery life of up to 30 hours on two AA batteries. Built-in Wi-Fi The new Xbox 360 is the only console with 802.11n Wi-Fi built-in for a faster and easier connection to Xbox LIVE. Stream HD movies and TV or download games from Xbox LIVE in 1080p and 5.1 surround sound from anywhere in the house. Compatible with b/g/n networks.",
"link": "http://clickfrom.buy.com/default.asp?adid=17379&sURL=http%3A%2F%2Fwww.buy.com%2Fprod%2Fxbox-360-system-4gb%2F216907636.html",
"brand": "Microsoft",
"condition": "new",
"gtin": "00885370138405",
"gtins": [
"00885370138405"
],
"inventories": [
{
"channel": "online",
"availability": "inStock",
"price": 199.99,
"shipping": 0.0,
"currency": "USD"
}
],
"images": [
{
"link": "http://ak.buy.com/PI/0/1000/216907636.jpg"
}
]
}
},
{
"kind": "shopping#product",
"id": "tag:google.com,2010:shopping/products/1113342/2934483943836745321",
"selfLink": "https://www.googleapis.com/shopping/search/v1/public/products/1113342/gid/2934483943836745321?alt=json",
"product": {
"googleId": "2934483943836745321",
"author": {
"name": "Walmart",
"accountId": "1113342"
},
"creationTime": "2011-03-25T21:44:47.000Z",
"modificationTime": "2011-12-08T01:12:50.000Z",
"country": "US",
"language": "en",
"title": "Xbox 360 250gb Console",
"description": "The new Xbox 360 250GB console. It's here today and ready for tomorrow, with a brand-new, leaner machine in an all-new black gloss finish. Wi-Fi is built in for easier connection to the world of entertainment on Xbox LIVE, where HD movies and TV stream in an instant. It's ready for the controller-free experiences of Kinect you don't just play the game; you are the game. Kinect brings games and entertainment to life in extraordinary new ways no controller required. Easy to use and instantly f",
"link": "http://www.walmart.com/catalog/product.do?product_id=14683340&sourceid=1500000000000003142040&ci_src=14110944&ci_sku=14683340",
"brand": "Microsoft",
"condition": "new",
"gtin": "00885370127119",
"gtins": [
"00885370127119"
],
"inventories": [
{
"channel": "online",
"availability": "inStock",
"price": 299.0,
"shipping": 7.97,
"currency": "USD"
}
],
"images": [
{
"link": "http://i.walmartimages.com/i/p/00/88/53/70/12/0088537012711_500X500.jpg"
}
]
}
}
I want to get all the values from price and store them into an array in php? How do I run this query on somepage.php and output the json values into a php array within that page?
The solution to this problem, in steps:
Retrieve the remote source text
Decode the JSON string into an array
Iterate over the resulting array to retrieve your desired data.
There are multiple ways to retrieve remote files/text in php. The most prominent are ...
Using file_get_contents():
$txt = file_get_contents('http://www.example.com/');
echo $txt;
And PHP's curl functions:
$url = 'http://www.mysite.com';
$ch = curl_init($url);
// Tell curl_exec to return the text instead of sending it to STDOUT
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Don't include return header in output
curl_setopt($ch, CURLOPT_HEADER, 0);
$txt = curl_exec($ch);
curl_close($ch);
echo $txt;
curl is generally a better option because you more control over the exact request parameters and more possibilities for error handling when things don't go as planned.
If the remote API page returns a JSON string, you turn it into an array using json_decode() and iterate the resulting array to pull out the values you want:
// retrieve the remote text using one of the above methods
$txt = file_get_contents('http://www.example.com/');
// decode the json string into an array
$arr = json_decode($txt);
$price_arr = array();
foreach ($arr as $a) {
// this is not the exact format of the data returned
// from the API, just an example to demonstrate how you
// would iterate over the decoded array
$price_arr[] = $a['price'];
}
You could also use PHP's array_map() function for more detailed parsing of the array that results from decoding the JSON string, though a simple foreach loop will suffice for most people.