How to use NewsAPI in Laravel - php

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...

Related

Organize JSON from PHP Loop

Good night, i have a file in JSON and I need to organize it by ticket, bringing their subjects from each ticket but I'm not able to do this loop. Can someone help me?
I have 25 of these tickets, here and an example of the structure.
[
{
"TicketID": 28890,
"CategoryID": 57526,
"CustomerID": 97979,
"CustomerName": "Cox Workman",
"CustomerEmail": "cox.workman#seges.com.br",
"DateCreate": "2017-12-13 03:08:42",
"DateUpdate": "2018-01-04 09:18:25",
"Interactions": [
{
"Subject": "Without Subject",
"Message": "I'm looking for men's shorts With side pockets 100 percent polyester.",
"DateCreate": "2017-12-13 03:08:42",
"Sender": "Customer"
},
{
"Subject": "RE: Without Subject",
"Message": "Hello! How are you? We don't have this model: / We have other models on the site, take a look.",
"DateCreate": "2018-01-03 09:18:25",
"Sender": "Expert"
},
{
"Subject": "RE: Without Subject",
"Message": "Thank you. GO shorts like with side pockets. Who made this model?",
"DateCreate": "2018-01-04 09:18:25",
"Sender": "Customer"
}
]
},
{
"TicketID": 28891,
"CategoryID": 46403,
"CustomerID": 97974,
"CustomerName": "Vilma Mcmahon",
"CustomerEmail": "vilma.mcmahon#seges.com.br",
"DateCreate": "2017-12-25 03:12:39",
"DateUpdate": "2018-02-12 05:14:11",
"Interactions": [
{
"Subject": "Complaint",
"Message": "Good night! I bought a shoe for my daughter at the store, but it is staining the sock, see the photos; What can I do to not ruin all the socks ???",
"DateCreate": "2017-12-25 03:12:39",
"Sender": "Customer"
},
{
"Subject": "RE: Complaint",
"Message": "Good morning How are you? We hope so! Wow, a shame it happened with tennis ... In this case, there is a different warranty for 12 months, and to offer this guarantee, the brand defines that for cases of defects, the evaluation is done directly with them, to evaluate the defect and already issue the authorization code for the exchange. As soon as the code is issued, just go to the store with the product to exchange! ",
"DateCreate": "2018-02-12 05:14:11",
"Sender": "Expert"
}
]
}
$subjects = array();
$json = json_decode($input);
foreach($json as $ticket){
print_r($ticket->Interactions);
foreach($ticket->Interactions as $interaction){
$subjects[] = $interaction->Subject;
}
}
print_r($subjects);
Not sure what you're trying to achieve, but $subjects there should contain all the subjects in every interactions of every ticket.

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].

Make table of object in PHP for JSON return

I'm using this script in order to make json :
<?php
header('Content-Type: application/json');
$feed = new DOMDocument();
$feed->load("http://www.feedforall.com/sample.xml");
//$feed->load($_GET['url']);
$json = array();
$json['title'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$json['description'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
$json['link'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('link')->item(0)->firstChild->nodeValue;
$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');
$json['item'] = array();
$i = 0;
foreach($items as $item) {
$title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$description = $item->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
$pubDate = $item->getElementsByTagName('pubDate')->item(0)->firstChild->nodeValue;
$guid = $item->getElementsByTagName('guid')->item(0)->firstChild->nodeValue;
$json['item'][$i++]['title'] = $title;
$json['item'][$i++]['description'] = $description;
$json['item'][$i++]['pubdate'] = $pubDate;
$json['item'][$i++]['guid'] = $guid;
}
echo json_encode($json);
?>
In the foreach loop, it takes all the item of the feed one by one and put them in item php table.
When I return, there is no table, all item properties are sent flat:
{
"title": "FeedForAll Sample Feed",
"description": "RSS is a fascinating technology. The uses for RSS are expanding daily. Take a closer look at how various industries are using the benefits of RSS in their businesses.",
"link": "http://www.feedforall.com/industry-solutions.htm",
"item": [
{
"title": "RSS Solutions for Restaurants"
},
{
"description": "<b>FeedForAll </b>helps Restaurant's communicate with customers. Let your customers know the latest specials or events.<br>\n<br>\nRSS feed uses include:<br>\n<i><font color=\"#FF0000\">Daily Specials <br>\nEntertainment <br>\nCalendar of Events </i></font>"
},
{},
{},
{
"title": "RSS Solutions for Schools and Colleges"
},
{
"description": "FeedForAll helps Educational Institutions communicate with students about school wide activities, events, and schedules.<br>\n<br>\nRSS feed uses include:<br>\n<i><font color=\"#0000FF\">Homework Assignments <br>\nSchool Cancellations <br>\nCalendar of Events <br>\nSports Scores <br>\nClubs/Organization Meetings <br>\nLunches Menus </i></font>"
},
{
"pubdate": "Tue, 19 Oct 2004 11:09:09 -0400"
},
{
"guid": null
},
{
"title": "RSS Solutions for Computer Service Companies"
},
{
"description": "FeedForAll helps Computer Service Companies communicate with clients about cyber security and related issues. <br>\n<br>\nUses include:<br>\n<i><font color=\"#0000FF\">Cyber Security Alerts <br>\nSpecials<br>\nJob Postings </i></font>"
},
{
"pubdate": "Tue, 19 Oct 2004 11:09:07 -0400"
},
{
"guid": null
},
{
"title": "RSS Solutions for Governments"
},
{
"description": "FeedForAll helps Governments communicate with the general public about positions on various issues, and keep the community aware of changes in important legislative issues. <b><i><br>\n</b></i><br>\nRSS uses Include:<br>\n<i><font color=\"#00FF00\">Legislative Calendar<br>\nVotes<br>\nBulletins</i></font>"
},
{
"pubdate": "Tue, 19 Oct 2004 11:09:05 -0400"
},
{
"guid": null
},
{
"title": "RSS Solutions for Politicians"
},
{
"description": "FeedForAll helps Politicians communicate with the general public about positions on various issues, and keep the community notified of their schedule. <br>\n<br>\nUses Include:<br>\n<i><font color=\"#FF0000\">Blogs<br>\nSpeaking Engagements <br>\nStatements<br>\n </i></font>"
},
{
"pubdate": "Tue, 19 Oct 2004 11:09:03 -0400"
},
{
"guid": null
},
{
"title": "RSS Solutions for Meteorologists"
},
{
"description": "FeedForAll helps Meteorologists communicate with the general public about storm warnings and weather alerts, in specific regions. Using RSS meteorologists are able to quickly disseminate urgent and life threatening weather warnings. <br>\n<br>\nUses Include:<br>\n<i><font color=\"#0000FF\">Weather Alerts<br>\nPlotting Storms<br>\nSchool Cancellations </i></font>"
},
{
"pubdate": "Tue, 19 Oct 2004 11:09:01 -0400"
},
{
"guid": null
},
{
"title": "RSS Solutions for Realtors & Real Estate Firms"
},
{
"description": "FeedForAll helps Realtors and Real Estate companies communicate with clients informing them of newly available properties, and open house announcements. RSS helps to reach a targeted audience and spread the word in an inexpensive, professional manner. <font color=\"#0000FF\"><br>\n</font><br>\nFeeds can be used for:<br>\n<i><font color=\"#FF0000\">Open House Dates<br>\nNew Properties For Sale<br>\nMortgage Rates</i></font>"
},
{
"pubdate": "Tue, 19 Oct 2004 11:08:59 -0400"
},
{
"guid": null
},
{
"title": "RSS Solutions for Banks / Mortgage Companies"
},
{
"description": "FeedForAll helps <b>Banks, Credit Unions and Mortgage companies</b> communicate with the general public about rate changes in a prompt and professional manner. <br>\n<br>\nUses include:<br>\n<i><font color=\"#0000FF\">Mortgage Rates<br>\nForeign Exchange Rates <br>\nBank Rates<br>\nSpecials</i></font>"
},
{
"pubdate": "Tue, 19 Oct 2004 11:08:57 -0400"
},
{
"guid": null
},
{
"title": "RSS Solutions for Law Enforcement"
},
{
"description": "<b>FeedForAll</b> helps Law Enforcement Professionals communicate with the general public and other agencies in a prompt and efficient manner. Using RSS police are able to quickly disseminate urgent and life threatening information. <br>\n<br>\nUses include:<br>\n<i><font color=\"#0000FF\">Amber Alerts<br>\nSex Offender Community Notification <br>\nWeather Alerts <br>\nScheduling <br>\nSecurity Alerts <br>\nPolice Report <br>\nMeetings</i></font>"
},
{
"pubdate": "Tue, 19 Oct 2004 11:08:56 -0400"
},
{
"guid": null
}
]
}
So What is the mistake? I was thinking that the fact to put tables in item should work but apparently not :-/ How Can I make them looks more like items in this one?
{
"status": "ok",
"feed": {
"url": "http://www.feedforall.com/sample.xml",
"title": "FeedForAll Sample Feed",
"link": "http://www.feedforall.com/industry-solutions.htm",
"author": "",
"description": "RSS is a fascinating technology. The uses for RSS are expanding daily. Take a closer look at how various industries are using the benefits of RSS in their businesses.",
"image": "http://www.feedforall.com/ffalogo48x48.gif"
},
"items": [
{
"title": "RSS Solutions for Restaurants",
"pubDate": "2004-10-19 15:09:11",
"link": "http://www.feedforall.com/restaurant.htm",
"guid": "db4b074250d7eedba34de1c872724ebd",
"author": "",
"thumbnail": "",
"description": "\n<b>FeedForAll </b>helps Restaurant's communicate with customers. Let your customers know the latest specials or events.<br><br>\nRSS feed uses include:<br><i>Daily Specials <br>\nEntertainment <br>\nCalendar of Events </i>\n",
"content": "\n<b>FeedForAll </b>helps Restaurant's communicate with customers. Let your customers know the latest specials or events.<br><br>\nRSS feed uses include:<br><i>Daily Specials <br>\nEntertainment <br>\nCalendar of Events </i>\n",
"enclosure": [],
"categories": [
"Computers/Software/Internet/Site Management/Content Management"
]
},
{
"title": "RSS Solutions for Schools and Colleges",
"pubDate": "2004-10-19 15:09:09",
"link": "http://www.feedforall.com/schools.htm",
"guid": "315ce482517f7e1d2d50f5a68d0e64fc",
"author": "",
"thumbnail": "",
"description": "FeedForAll helps Educational Institutions communicate with students about school wide activities, events, and schedules.<br><br>\nRSS feed uses include:<br><i>Homework Assignments <br>\nSchool Cancellations <br>\nCalendar of Events <br>\nSports Scores <br>\nClubs/Organization Meetings <br>\nLunches Menus </i>\n",
"content": "FeedForAll helps Educational Institutions communicate with students about school wide activities, events, and schedules.<br><br>\nRSS feed uses include:<br><i>Homework Assignments <br>\nSchool Cancellations <br>\nCalendar of Events <br>\nSports Scores <br>\nClubs/Organization Meetings <br>\nLunches Menus </i>\n",
"enclosure": [],
"categories": [
"Computers/Software/Internet/Site Management/Content Management"
]
},
{
"title": "RSS Solutions for Computer Service Companies",
"pubDate": "2004-10-19 15:09:07",
"link": "http://www.feedforall.com/computer-service.htm",
"guid": "7973f3583dd2e760f6e1385a90cf87a8",
"author": "",
"thumbnail": "",
"description": "FeedForAll helps Computer Service Companies communicate with clients about cyber security and related issues. <br><br>\nUses include:<br><i>Cyber Security Alerts <br>\nSpecials<br>\nJob Postings </i>\n",
"content": "FeedForAll helps Computer Service Companies communicate with clients about cyber security and related issues. <br><br>\nUses include:<br><i>Cyber Security Alerts <br>\nSpecials<br>\nJob Postings </i>\n",
"enclosure": [],
"categories": [
"Computers/Software/Internet/Site Management/Content Management"
]
},
{
"title": "RSS Solutions for Governments",
"pubDate": "2004-10-19 15:09:05",
"link": "http://www.feedforall.com/government.htm",
"guid": "d6131efb3d938b112ab861b97434942a",
"author": "",
"thumbnail": "",
"description": "FeedForAll helps Governments communicate with the general public about positions on various issues, and keep the community aware of changes in important legislative issues. <b><i><br></i></b><br>\nRSS uses Include:<br><i>Legislative Calendar<br>\nVotes<br>\nBulletins</i>\n",
"content": "FeedForAll helps Governments communicate with the general public about positions on various issues, and keep the community aware of changes in important legislative issues. <b><i><br></i></b><br>\nRSS uses Include:<br><i>Legislative Calendar<br>\nVotes<br>\nBulletins</i>\n",
"enclosure": [],
"categories": [
"Computers/Software/Internet/Site Management/Content Management"
]
},
{
"title": "RSS Solutions for Politicians",
"pubDate": "2004-10-19 15:09:03",
"link": "http://www.feedforall.com/politics.htm",
"guid": "d01522b2d34449e665339b1c64500492",
"author": "",
"thumbnail": "",
"description": "FeedForAll helps Politicians communicate with the general public about positions on various issues, and keep the community notified of their schedule. <br><br>\nUses Include:<br><i>Blogs<br>\nSpeaking Engagements <br>\nStatements<br></i>\n",
"content": "FeedForAll helps Politicians communicate with the general public about positions on various issues, and keep the community notified of their schedule. <br><br>\nUses Include:<br><i>Blogs<br>\nSpeaking Engagements <br>\nStatements<br></i>\n",
"enclosure": [],
"categories": [
"Computers/Software/Internet/Site Management/Content Management"
]
},
{
"title": "RSS Solutions for Meteorologists",
"pubDate": "2004-10-19 15:09:01",
"link": "http://www.feedforall.com/weather.htm",
"guid": "5273191196b584a4c5a98017d5a1b1d6",
"author": "",
"thumbnail": "",
"description": "FeedForAll helps Meteorologists communicate with the general public about storm warnings and weather alerts, in specific regions. Using RSS meteorologists are able to quickly disseminate urgent and life threatening weather warnings. <br><br>\nUses Include:<br><i>Weather Alerts<br>\nPlotting Storms<br>\nSchool Cancellations </i>\n",
"content": "FeedForAll helps Meteorologists communicate with the general public about storm warnings and weather alerts, in specific regions. Using RSS meteorologists are able to quickly disseminate urgent and life threatening weather warnings. <br><br>\nUses Include:<br><i>Weather Alerts<br>\nPlotting Storms<br>\nSchool Cancellations </i>\n",
"enclosure": [],
"categories": [
"Computers/Software/Internet/Site Management/Content Management"
]
},
{
"title": "RSS Solutions for Realtors & Real Estate Firms",
"pubDate": "2004-10-19 15:08:59",
"link": "http://www.feedforall.com/real-estate.htm",
"guid": "ce3eb8e9a2370c05babd1f4d67796e03",
"author": "",
"thumbnail": "",
"description": "FeedForAll helps Realtors and Real Estate companies communicate with clients informing them of newly available properties, and open house announcements. RSS helps to reach a targeted audience and spread the word in an inexpensive, professional manner. <br><br>\nFeeds can be used for:<br><i>Open House Dates<br>\nNew Properties For Sale<br>\nMortgage Rates</i>\n",
"content": "FeedForAll helps Realtors and Real Estate companies communicate with clients informing them of newly available properties, and open house announcements. RSS helps to reach a targeted audience and spread the word in an inexpensive, professional manner. <br><br>\nFeeds can be used for:<br><i>Open House Dates<br>\nNew Properties For Sale<br>\nMortgage Rates</i>\n",
"enclosure": [],
"categories": [
"Computers/Software/Internet/Site Management/Content Management"
]
},
{
"title": "RSS Solutions for Banks / Mortgage Companies",
"pubDate": "2004-10-19 15:08:57",
"link": "http://www.feedforall.com/banks.htm",
"guid": "548e21e2baaba66f6cf56a92d72fa85a",
"author": "",
"thumbnail": "",
"description": "FeedForAll helps <b>Banks, Credit Unions and Mortgage companies</b> communicate with the general public about rate changes in a prompt and professional manner. <br><br>\nUses include:<br><i>Mortgage Rates<br>\nForeign Exchange Rates <br>\nBank Rates<br>\nSpecials</i>\n",
"content": "FeedForAll helps <b>Banks, Credit Unions and Mortgage companies</b> communicate with the general public about rate changes in a prompt and professional manner. <br><br>\nUses include:<br><i>Mortgage Rates<br>\nForeign Exchange Rates <br>\nBank Rates<br>\nSpecials</i>\n",
"enclosure": [],
"categories": [
"Computers/Software/Internet/Site Management/Content Management"
]
},
{
"title": "RSS Solutions for Law Enforcement",
"pubDate": "2004-10-19 15:08:56",
"link": "http://www.feedforall.com/law-enforcement.htm",
"guid": "6e4ab6d2fee3c163f22e07ac8df11421",
"author": "",
"thumbnail": "",
"description": "\n<b>FeedForAll</b> helps Law Enforcement Professionals communicate with the general public and other agencies in a prompt and efficient manner. Using RSS police are able to quickly disseminate urgent and life threatening information. <br><br>\nUses include:<br><i>Amber Alerts<br>\nSex Offender Community Notification <br>\nWeather Alerts <br>\nScheduling <br>\nSecurity Alerts <br>\nPolice Report <br>\nMeetings</i>\n",
"content": "\n<b>FeedForAll</b> helps Law Enforcement Professionals communicate with the general public and other agencies in a prompt and efficient manner. Using RSS police are able to quickly disseminate urgent and life threatening information. <br><br>\nUses include:<br><i>Amber Alerts<br>\nSex Offender Community Notification <br>\nWeather Alerts <br>\nScheduling <br>\nSecurity Alerts <br>\nPolice Report <br>\nMeetings</i>\n",
"enclosure": [],
"categories": [
"Computers/Software/Internet/Site Management/Content Management"
]
}
]
}
You are incrementing the counter for every property. As it is set to 0 to start with, you should only do that at the end:
$json['item'][$i++]['title'] = $title;
$json['item'][$i++]['description'] = $description;
$json['item'][$i++]['pubdate'] = $pubDate;
$json['item'][$i++]['guid'] = $guid;
should be:
$json['item'][$i]['title'] = $title;
$json['item'][$i]['description'] = $description;
$json['item'][$i]['pubdate'] = $pubDate;
$json['item'][$i]['guid'] = $guid;
# Increment the counter for the next iteration
$i++;
You're incrementing $i each time you add a new item. Try this:
$json['item'][$i++] = array(
'title' => $title,
'description' => $description,
'pubdate' => $pubDate,
'guid' => $guid,
);
Or:
$json['item'][$i]['title'] = $title;
$json['item'][$i]['description'] = $description;
$json['item'][$i]['pubdate'] = $pubDate;
$json['item'][$i]['guid'] = $guid;
$i++;

How can I get all Video IDs form a YouTube Channel by using YouTube API?

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.

Google Api Gather Results in Php Array()

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.

Categories