Posted: . At: 8:30 AM. This was 7 months ago. Post ID: 18470
Page permalink. WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters.
These cookies expire two weeks after they are set.


A very nice PHP example to parse a JSON file.


This PHP example will parse a JSON file and then print the contents. I think this is a very useful file. The JSON file has sublevels, but this may be flattened and easily dealt with by a foreach loop.

weather.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<html>
    <head>
        <title>Weather in Sydney 2000.</title>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <meta name="description" content="Dailymail videos page. Find all news and showbiz videos here." />
          <meta name="keywords" content="videos,australia,mail,free,playlist" />
    </head>
 
<body>
 
    <p>Weather in Sydney</p>
 
    <?php
        $json = file_get_contents("2000.json");
 
        $data = json_decode($json, true);
 
        function flattenArray($array, $prefix = "") {
            $result = [];
            foreach ($array as $key => $value) {
                if (is_array($value)) {
                    $result = array_merge($result, flattenArray($value, $prefix . $key . "_"));
                } else {
                    $result[$prefix . $key] = $value;
                }
            }
            return $result;
        }
 
        $flatData = flattenArray($data);
 
        foreach ($flatData as $key => $value) {
            echo "<p>". $key . ": " . $value . "</p>" . PHP_EOL;
        }
 
    ?>
 
</body>
<html>

This function is what we need. This merges multiple arrays into one and then allows further manipulation of the data.

weather.php
21
22
23
24
25
26
27
28
29
30
31
        function flattenArray($array, $prefix = "") {
            $result = [];
            foreach ($array as $key => $value) {
                if (is_array($value)) {
                    $result = array_merge($result, flattenArray($value, $prefix . $key . "_"));
                } else {
                    $result[$prefix . $key] = $value;
                }
            }
            return $result;
        }

This is the JSON file I am parsing this supplies the weather data for Sydney NSW, 2000. But I can not parse it directly for some reason, you need to download it locally and then parse it. But this does work.

https://www.news.com.au/wp-json/api/weather/2000.

This might be a very helpful PHP example when attempting to parse a JSON file. I hope you find this to be very useful.


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.