Как разобрать JSON в Php Разделить и перебрать данные

Raja Osama спросил: 12 мая 2018 в 03:51 в: php

Привет,,

Я хотел знать, что я использую API, этот API дает мне новости в формате JSON. Теперь я делаю сайт, на котором будут все эти новости. Я не могу разобрать этот JSON DATA, это URL-адрес, который содержит эти данные. 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"
        }
    ]
}

И мой код Php расшифровывает эти данные в массив, а затем после этого я могу Разделите объекты и массивы. Я знаю, сколько результатов у меня есть, и я могу просто пропустить его, но мне нужно знать, как я могу получить эти данные.

    <?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"];?>

2 ответа

Есть решение
Diblo Dk ответил: 12 мая 2018 в 05:05

Ваш код PHP неверен, echo $jsons[0]["article"];. - Это не сработает. Вам нужно заменить его на print_r( $jsons["articles"][0] );. Поэтому, я думаю, что вы подразумеваете под JSON DATA, так это то, как вы откатываете или просматриваете данные.

Поскольку вы установили параметр assoc в true, json_decode() вернет массив .

Сначала сделаем поправку на ваш код, который, надеюсь, поможет вам понять, как работают json и array().

$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'];

В этом примере мы будет раскрывать все статьи.

$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 '<a href="' . $article['url'] . '">Read more</a>';
}

Вы также можете увидеть массив () на w3schools.com.

Raja Osama ответил: 12 мая 2018 в 04:54
Отличная работа как шарм. Ну, помогите мне немного больше. Например, я хочу получить $ json ['totalResults'], но это, похоже, не работает.
Diblo Dk ответил: 12 мая 2018 в 05:04
Замените $json на $jsons, например $jsons['totalResults']. Вы можете переименовать переменную $jsons в $news, чтобы ее было легче понять.
Diblo Dk ответил: 12 мая 2018 в 05:10
json_decode() принимает закодированную JSON строку и преобразует ее в переменную PHP . В вашем случае массив PHP.
Raja Osama ответил: 12 мая 2018 в 05:24
Да, брат, это была проблема, спасибо мне, спасибо, что помог мне. быстрый вопрос, почему все здесь так грубо, что они просто просто downvote, как только я публикую что-нибудь.
Diblo Dk ответил: 12 мая 2018 в 06:01
Я лично думаю, что ваш вопрос был неясным, но мы получили его. Я думаю, что слишком легко сказать, что вы можете все узнать, просто прочитав (по исследованиям). Я также думаю, что ваш вопрос бесполезен только для опытных кодов. Поэтому я бы не стал понижать вас, и я не согласен с правилами сообщества, потому что должно быть место для всех, как 7 лет назад :). Поэтому я не могу дать вам ясную причину, по которой вы стали downvote, потому что меня больше не интересуют правила сообщества;)
Über ответил: 12 мая 2018 в 04:13

$jsons - это не массив, а объект. Вы хотите $jsons->articles[0].

Diblo Dk ответил: 12 мая 2018 в 04:25
Это массив, потому что он установил параметр assoc в true php.net/manual/en/function.json-decode.php
Über ответил: 12 мая 2018 в 05:15
Я забыл об этой части. Должно быть $jsons['articles'][0]. Кстати, спасибо за проголосовать.