Home > Backend Development > PHP Tutorial > How to Properly Parse Nested JSON Data in PHP?

How to Properly Parse Nested JSON Data in PHP?

Barbara Streisand
Release: 2024-11-16 01:15:03
Original
796 people have browsed it

How to Properly Parse Nested JSON Data in PHP?

Parsing JSON Objects in PHP with json_decode

When attempting to retrieve weather data from a JSON-formatted web service, you may encounter challenges. A common PHP request code that doesn't succeed:

$url = "http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
echo $data[0]->weather->weatherIconUrl[0]->value;
Copy after login

To understand the issue, let's examine the JSON data you received:

{
  "data": {
    "current_condition": [...],
    "request": [...],
    "weather": [
      {
        "date": "2010-10-27",
        "precipMM": "0.0",
        "tempMaxC": "3",
        "tempMaxF": "38",
        "tempMinC": "-13",
        "tempMinF": "9",
        "weatherCode": "113",
        "weatherDesc": [{ "value": "Sunny" }],
        "weatherIconUrl": [{ "value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png" }],
        "winddir16Point": "N",
        "winddirDegree": "356",
        "winddirection": "N",
        "windspeedKmph": "5",
        "windspeedMiles": "3"
      },
      ...
    ]
  }
}
Copy after login

Notice that the weather data is nested within the "data" object. Therefore, to correctly parse the JSON, you need to modify your code:

$url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710';
$content = file_get_contents($url);
$json = json_decode($content, true);

foreach ($json['data']['weather'] as $item) {
    print $item['date'];
    print ' - ';
    print $item['weatherDesc'][0]['value'];
    print ' - ';
    print '<img src="' . $item['weatherIconUrl'][0]['value'] . '" border="0" alt="" />';
    print '<br>';
}
Copy after login

Setting the second parameter of json_decode to true gives you an array, allowing you to access data using array indexing. The JSONview Firefox extension can also help visualize JSON structures and simplify parsing.

The above is the detailed content of How to Properly Parse Nested JSON Data in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template