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.
Related
I want to build a website and insert news articles.
I found a free newsAPI website and I got apikey as below:
https://newsapi.org/v1/articles?source=techcrunch&apiKey=3329a36068a14512b9acb66f2b8f800a
I want to my website has a Live News and display some top news. but I don't know how to write proper code in Laravel. I have tried below code and only display image. I don't know how to display author, tile, description,url, etc. like newsAPI website live response. Appreciate if someone could help me.
<?php
$urlArticles = file_get_contents('https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=3329a36068a14512b9acb66f2b8f800a');
$urlArticlesArray = json_decode($urlArticles, true);
$articles = $urlArticlesArray['articles'];
for($i = 0; $i < count($articles); $i++) {
$sites = $urlArticlesArray['articles'][$i];
echo '<img src="'.$sites['urlToImage'].'">';
}
?>
newsAPI website Live response example:
{
"status": "ok",
"source": "techcrunch",
"sortBy": "top",
-"articles": [
-{
"author": "Lucas Matney",
"title": "Gadgets",
"description": "Product reviews and demos from our TechCrunch Gadget team",
"url": "https://techcrunch.com/video/gadgets/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2013/10/techcrunch-gadgets-icon_rect.png?w=450&h=200&crop=1",
"publishedAt": "2017-04-07T23:00:45Z"
},
-{
"author": "Romain Dillet",
"title": "Uber is now banned in Italy for unfair competition",
"description": "While Uber is fighting Waymo at home, the American company is also having issues abroad. As Reuters reported, an Italian court has ordered Uber to stop all..",
"url": "https://techcrunch.com/2017/04/09/uber-is-now-banned-in-italy-for-unfair-competition/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2014/02/uber.jpg?w=764&h=400&crop=1",
"publishedAt": "2017-04-09T09:53:47Z"
},
-{
"author": "Ryan Lawler",
"title": "Gig economy stalwart TaskRabbit is contemplating a sale",
"description": "One of the earliest and most prominent startups of the so-called \"sharing economy\" or \"gig economy,\" is evaluating the possibility of selling itself. As..",
"url": "https://techcrunch.com/2017/04/08/taskrabbit-acquisition-maybe/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2015/01/taskrabbit-fire.png?w=764&h=400&crop=1",
"publishedAt": "2017-04-08T23:44:34Z"
},
-{
"author": "Ryan Lawler",
"title": "Netflix’s long-time chief product officer Neil Hunt is leaving the company",
"description": "Streaming video provider Netflix is making a change in its senior management, as the company announced long-time chief product officer Neil Hunt will be..",
"url": "https://techcrunch.com/2017/04/08/netflix-neil-hunt-leaving/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/04/los-gatos_01.jpg?w=764&h=400&crop=1",
"publishedAt": "2017-04-08T21:30:52Z"
},
-{
"author": "Natasha Lomas",
"title": "Postepic is an app for elegantly sharing book quotes",
"description": "Postepic wants to liberate all those interesting text snippets you have languishing on your camera roll and turn them into visually appealing quotations ready..",
"url": "https://techcrunch.com/2017/04/08/postepic-is-an-app-for-elegantly-sharing-book-quotes/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/04/p1050418.jpg?w=764&h=400&crop=1",
"publishedAt": "2017-04-08T16:00:31Z"
}
]
}
OK, first: I would use something like Guzzle to call external sources....
Guzzle Docs
Then, in your code...
$client = new GuzzleHttp\Client();
$url = 'https://.....';
$response = $client->get(url);
dd($response->getStatusCode()); // will dump the statuscode
dd($response->getBody()); // will dump the body
$body = $response->getBody(); //assign body to var
etc...
How to get Deeplinks in JSON format with PHP?
This is the JSON object I actually have
{
"_type": "SearchResponse",
"webPages": {
"webSearchUrl": "https:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=sFk5GtkV8PxaqVq0K3GniaQOQJqKR2jqw1udftLC9QE&v=1&r=https%3a%2f%2fwww.bing.com%2fsearch%3fq%3dcontemporary%2bfurniture&p=DevEx,5336.1",
"totalEstimatedMatches": 46000000,
"value": [{
"id": "https:\/\/api.cognitive.microsoft.com\/api\/v5\/#WebPages.0",
"name": "Contemporary Furniture. Modern and Scandinavian designs.",
"url": "https:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=Q0wwocl-JR44YrK1RsR_5rSqO4KPlSPx0KgUi-sMocA&v=1&r=https%3a%2f%2fcontemporaryfurniture.com%2f&p=DevEx,5080.1",
"displayUrl": "https:\/\/contemporaryfurniture.com",
"snippet": "The finest in contemporary and modern furniture. Imported and domestic styles, bedrooms, sofas, home office, more. Shop online or visit our NY showroom.",
"deepLinks": [{
"name": "Bedrooms",
"url": "https:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=jo1rIVengiXnaKOkFczZ54qrp9-L4W2jb1sJ41jl04g&v=1&r=https%3a%2f%2fwww.contemporaryfurniture.com%2fshop%2fbedrooms-19%2f&p=DevEx,5072.1",
"snippet": "Bedroom sets including beds, dressers, nightstands and chests. Produced in various woods and lacquers. Contemporary, scandinavian and modern designs."
}, {
"name": "Dining Rooms",
"url": "https:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=EsyLPbUccu5BzwCeceP_S5u46vo4gSDMG7vP29BfjFE&v=1&r=https%3a%2f%2fwww.contemporaryfurniture.com%2fshop%2fdining-rooms-12%2f&p=DevEx,5073.1",
"snippet": "Dining Room sets, dining tables, servers, buffet and china cabinets. Contemporary and Scandinavian styles."
}, {
"name": "Barstool",
"url": "https:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=6rOwsJH4uT4LzjG833eSRYQgDMCKiogHGdgnokFVSEg&v=1&r=https%3a%2f%2fwww.contemporaryfurniture.com%2fshop%2fbarstool-16%2f&p=DevEx,5074.1",
"snippet": "Barstools and counterstools contemporary, modern and scandinavian designs produced in wood and metal."
}, {
"name": "Chairs",
"url": "https:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=ADlw0i43aQhdLC0tHBfjMFjYwiWYHZ3ggdG6RhZv9ss&v=1&r=https%3a%2f%2fwww.contemporaryfurniture.com%2fshop%2fchairs-13%2f&p=DevEx,5075.1",
"snippet": "Chairs to compliment your living room produced in fabric upholstery and leather. Contemporary and modern designs."
}],
"dateLastCrawled": "2017-03-31T17:25:00"
}, {
"id": "https:\/\/api.cognitive.microsoft.com\/api\/v5\/#WebPages.1",
"name": "Contemporary Furniture | Houzz",
"url": "http:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=vsM0va_8kehN5ZnPil2frs3eKL16FOHnut88FvEHRsM&v=1&r=http%3a%2f%2fwww.houzz.com%2fphotos%2fcontemporary%2ffurniture&p=DevEx,5098.1",
"displayUrl": "www.houzz.com\/photos\/contemporary\/furniture",
"snippet": "Browse a wide selection of contemporary furniture for sale on Houzz, including wood furniture and leather furniture for your dining room, office, bedroom and living room.",
"dateLastCrawled": "2017-03-30T22:51:00"
}, {
"id": "https:\/\/api.cognitive.microsoft.com\/api\/v5\/#WebPages.2",
"name": "Affordable Modern Furniture, Decor & Lighting online. Free ...",
"url": "https:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=OwOQI48E8ZhxF8xWw-iB2POJliBV0LIE3CucLePUzeg&v=1&r=https%3a%2f%2fwww.contemporaryfurniturewarehouse.com%2f&p=DevEx,5112.1",
"displayUrl": "https:\/\/www.contemporaryfurniturewarehouse.com",
"snippet": "Modern & Contemporary Furniture on sale. Shop for sofas, sectionals, accent chairs, dining chairs, bar stools, office chairs, stools, outdoor furniture & more.",
"dateLastCrawled": "2017-03-31T02:54:00"
}
And here is the code I did so far:
$i=1;
foreach($data->webPages->value as $val){
if($i==1){
$part = $val['deepLinks']->snippet;
}
$i++;
}
Results in: Fatal error: Cannot use object of type stdClass as array.
how to get that value?
I think it may have to do with $data. It isn't an Array.
Did you use json_decode() to turn your JSON object to a PHP variable? If yes, then you need to change it to:
json_decode($myJSON, true);
If set to true PHP will return an associative array but If not PHP it will return a object(stdClass).
You can read more about why that is here
If you want a flat array of deepLinks, try this:
$ret = [];
foreach($data->webPages->value as $val){
if(property_exists($val,"deepLinks")){
$ret = array_merge($ret, $val->deepLinks);
}
}
var_dump($ret);
I tested it and it works.
On the other hand, if you want to get it grouped:
$ret = [];
foreach($data->webPages->value as $val){
if(property_exists($val,"deepLinks")){
$ret[] = $val->deepLinks;
}
}
var_dump($ret);
The test JSON I've used:
$data = '{
"_type": "SearchResponse",
"webPages": {
"webSearchUrl": "https:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=sFk5GtkV8PxaqVq0K3GniaQOQJqKR2jqw1udftLC9QE&v=1&r=https%3a%2f%2fwww.bing.com%2fsearch%3fq%3dcontemporary%2bfurniture&p=DevEx,5336.1",
"totalEstimatedMatches": 46000000,
"value": [{
"id": "https:\/\/api.cognitive.microsoft.com\/api\/v5\/#WebPages.0",
"name": "Contemporary Furniture. Modern and Scandinavian designs.",
"url": "https:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=Q0wwocl-JR44YrK1RsR_5rSqO4KPlSPx0KgUi-sMocA&v=1&r=https%3a%2f%2fcontemporaryfurniture.com%2f&p=DevEx,5080.1",
"displayUrl": "https:\/\/contemporaryfurniture.com",
"snippet": "The finest in contemporary and modern furniture. Imported and domestic styles, bedrooms, sofas, home office, more. Shop online or visit our NY showroom.",
"deepLinks": [{
"name": "Bedrooms",
"url": "https:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=jo1rIVengiXnaKOkFczZ54qrp9-L4W2jb1sJ41jl04g&v=1&r=https%3a%2f%2fwww.contemporaryfurniture.com%2fshop%2fbedrooms-19%2f&p=DevEx,5072.1",
"snippet": "Bedroom sets including beds, dressers, nightstands and chests. Produced in various woods and lacquers. Contemporary, scandinavian and modern designs."
}, {
"name": "Dining Rooms",
"url": "https:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=EsyLPbUccu5BzwCeceP_S5u46vo4gSDMG7vP29BfjFE&v=1&r=https%3a%2f%2fwww.contemporaryfurniture.com%2fshop%2fdining-rooms-12%2f&p=DevEx,5073.1",
"snippet": "Dining Room sets, dining tables, servers, buffet and china cabinets. Contemporary and Scandinavian styles."
}, {
"name": "Barstool",
"url": "https:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=6rOwsJH4uT4LzjG833eSRYQgDMCKiogHGdgnokFVSEg&v=1&r=https%3a%2f%2fwww.contemporaryfurniture.com%2fshop%2fbarstool-16%2f&p=DevEx,5074.1",
"snippet": "Barstools and counterstools contemporary, modern and scandinavian designs produced in wood and metal."
}, {
"name": "Chairs",
"url": "https:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=ADlw0i43aQhdLC0tHBfjMFjYwiWYHZ3ggdG6RhZv9ss&v=1&r=https%3a%2f%2fwww.contemporaryfurniture.com%2fshop%2fchairs-13%2f&p=DevEx,5075.1",
"snippet": "Chairs to compliment your living room produced in fabric upholstery and leather. Contemporary and modern designs."
}],
"dateLastCrawled": "2017-03-31T17:25:00"
}, {
"id": "https:\/\/api.cognitive.microsoft.com\/api\/v5\/#WebPages.1",
"name": "Contemporary Furniture | Houzz",
"url": "http:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=vsM0va_8kehN5ZnPil2frs3eKL16FOHnut88FvEHRsM&v=1&r=http%3a%2f%2fwww.houzz.com%2fphotos%2fcontemporary%2ffurniture&p=DevEx,5098.1",
"displayUrl": "www.houzz.com\/photos\/contemporary\/furniture",
"snippet": "Browse a wide selection of contemporary furniture for sale on Houzz, including wood furniture and leather furniture for your dining room, office, bedroom and living room.",
"dateLastCrawled": "2017-03-30T22:51:00"
}]
}
}';
I completed the missing parts.
Is there any way to get all the video ids from a youtube channel?
The YouTube API v2 was depreciated last year. Spend some time looking into v3,...it's quite a bit different in that you'll need to make a series of calls to get the same thing you were getting in v2 and none of your old code will work, but has better control in other ways,...it's just awful chatty is all.
Lets take an example channel and its example video.
Now we have to get the channel_id from the video_id from its URL https://www.youtube.com/watch?v=PfrV_6yWbEgwe which is PfrV_6yWbEgwe
For getting the channel_id using the video_id, you can use the videos:list endpoint of the YouTube Data API - example.
Result:
{
"kind": "youtube#videoListResponse",
"etag": "qh1OskO-aIVgApaf_ko2NP56aTw",
"items": [
{
"kind": "youtube#video",
"etag": "eIO610C5Nr92qVJbX_pQYb9kc0Y",
"id": "PfrV_6yWbEg",
"snippet": {
"publishedAt": "2016-10-28T22:48:23Z",
"channelId": "UCulYu1HEIa7f70L2lYZWHOw",
"title": "Michael Jackson - Who Is It (Official Video)",
"description": "“Who Is It” by Michael Jackson\nListen to Michael Jackson: https://MichaelJackson.lnk.to/_listenYD\n\nMichael Jackson’s “Who Is It” short film, directed by David Fincher, spins a dark, expressionistic tale of heartbreak over a lover’s infidelity that complements this worldwide Top 10 hit song.\n\nFollow Michael Jackson:\nFacebook: https://MichaelJackson.lnk.to/followFI\nTwitter: https://MichaelJackson.lnk.to/followTI\nInstagram: https://MichaelJackson.lnk.to/followII\nWebsite: https://MichaelJackson.lnk.to/followWI\nSpotify: https://MichaelJackson.lnk.to/followSI\nYouTube: https://MichaelJackson.lnk.to/subscribeYD\n\nChorus:\nIs it a friend of mine\n(Who is it?)\nIs it my brother?\n(Who is it?)\nSomebody hurt my soul\n(Who is it?)\nI can't take this stuff no more\n\n#MichaelJackson #Dangerous #WhoIsIt",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/PfrV_6yWbEg/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/PfrV_6yWbEg/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/PfrV_6yWbEg/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "michaeljacksonVEVO",
"tags": [
"1991",
"new jack swing",
"Dangerous",
"Teddy Riley",
"fourth album",
"ocean way studios",
"record one studios",
"michael jackson",
"michael jackson Who Is It",
"michael jackson dangerous live",
"michael jackson dangerous album",
"michael jackson dangerous tour",
"michael jackson dangerous lyrics",
"michael jackson songs",
"beat it",
"billie jean",
"michael jackson pyt",
"michael jackson thriller",
"michael jackson black or white",
"smooth criminal",
"man in the mirror",
"why",
"you"
],
"categoryId": "10",
"liveBroadcastContent": "none",
"localized": {
"title": "Michael Jackson - Who Is It (Official Video)",
"description": "“Who Is It” by Michael Jackson\nListen to Michael Jackson: https://MichaelJackson.lnk.to/_listenYD\n\nMichael Jackson’s “Who Is It” short film, directed by David Fincher, spins a dark, expressionistic tale of heartbreak over a lover’s infidelity that complements this worldwide Top 10 hit song.\n\nFollow Michael Jackson:\nFacebook: https://MichaelJackson.lnk.to/followFI\nTwitter: https://MichaelJackson.lnk.to/followTI\nInstagram: https://MichaelJackson.lnk.to/followII\nWebsite: https://MichaelJackson.lnk.to/followWI\nSpotify: https://MichaelJackson.lnk.to/followSI\nYouTube: https://MichaelJackson.lnk.to/subscribeYD\n\nChorus:\nIs it a friend of mine\n(Who is it?)\nIs it my brother?\n(Who is it?)\nSomebody hurt my soul\n(Who is it?)\nI can't take this stuff no more\n\n#MichaelJackson #Dangerous #WhoIsIt"
},
"defaultAudioLanguage": "en-US"
}
}
],
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
}
}
In this case, the channel_id of the example video PfrV_6yWbEg is: UCulYu1HEIa7f70L2lYZWHOw.
Then, with this channel_id, change the second character to U as follows:
Unmodified: UCulYu1HEIa7f70L2lYZWHOw
Modified: UUulYu1HEIa7f70L2lYZWHOw
This modified id is the Uploads playlist of that said YouTube channel.
With this Uploads playlist_id, you can use the Playlistitem:list endpoint of the YouTube Data API to retrieve all the uploaded videos from the autogenerated channel.
This is the example with the uploads playlist_id described in this answer.
Context:
I'm building a website using Symfony2 (php) and I have already implemented a social(google) login function (through HWIOAuthBundle) that allows users to:
- register a new account using their own google account
- link a google account to an existing non-social account
As a result, in my database the users table already has a google_id field.
What I want to do:
Users must be able to submit youtube links of their own videos. These links will be saved in the database BUT first I need to verify that the video BELONGS(IS OWNED) to the user that is submitting the link. In other words: users CAN NOT submit videos uploaded by someone else.
I plan on using the Youtube API (php) that you can find on the google developers website.
Question(s):
How can I verify this condition? Can I use the Google Id that I already have in my users table? Or do I need to create a new youtube_id field because the id is different from the google_id? What api function/method should I call to verify the video ownership?
Ideas?
Try to check them by v3/videos - https://developers.google.com/youtube/v3/docs/videos/list
if you use "part=snippet"
you will see channel info in items->snippet->channelId and items->snippet->channelTitle
For example for https://www.youtube.com/watch?v=YVe2THgSDxc load
https://www.googleapis.com/youtube/v3/videos?id=YVe2THgSDxc&part=snippet&key=[YOUR_API_KEY]
You will get
{
"kind": "youtube#videoListResponse",
"etag": "*******",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#video",
"etag": "*******",
"id": "YVe2THgSDxc",
"snippet": {
"publishedAt": "2018-01-22T15:47:46.000Z",
"channelId": "UCiP6wD_tYlYLYh3agzbByWQ",
"title": "30 Minute HIIT Cardio*******",
"description": "Full info for thi*******.",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/YVe2THgSDxc/default.jpg",
"width": 120,
"height": 90
},
*******
},
"channelTitle": "FitnessBlender",
"tags": [
"fitness blender",
"fitness",
"blender",
"workout",
"workout videos",
"hiit workout",
"cardio workout",
"hiit cardio",
"cardio at home",
"hiit at home",
"at home hiit",
"at home workouts",
"free workout videos",
"hiit cardio workout",
"strength",
"strength training",
"strength training workout",
"dumbbell workout",
"at home strength training",
"strength and hiit",
"hiit and strength",
"lower body workout",
"butt workout",
"thigh workout",
"butt and thigh workout",
"fat burning workout",
"muscle building workout"
],
"categoryId": "26",
"liveBroadcastContent": "none",
"localized": {
"title": "30 Minute HIIT Ca*******",
"description": "Full info for this *******"
}
}
}
]
}
So if you have users's channelID or channelName you can compare it with video's channelID or channelName.
If you have user's name but haven't his channel list you can get it by v3/channels
For example this gets channel list for user "popsugartvfit"
https://www.googleapis.com/youtube/v3/channels?&part=contentDetails&forUsername=popsugartvfit&key=[YOUR_API_KEY]
You will get
{
"kind": "youtube#channelListResponse",
"etag": "*****",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#channel",
"etag": "*******",
"id": "UCBINFWq52ShSgUFEoynfSwg",
"contentDetails": {
"relatedPlaylists": {
"uploads": "UUBINFWq52ShSgUFEoynfSwg",
"watchHistory": "HL",
"watchLater": "WL"
}
}
}
]
}
And use if for validation
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 />";
}
}