Advertisement
  1. Code
  2. Cloud & Hosting

How to Parse JSON in PHP

Scroll to top

JSON, short for JavaScript Object Notation, is a common lightweight format for storing and exchanging information. As the name suggests, it was initially derived from JavaScript, but it is a language-independent format for storing information. A lot of languages like PHP now implement functions to read and create JSON data.

This tutorial will teach you how to read a JSON file and convert it to an array in PHP. Learn how to parse JSON using the json_decode() and json_encode() functions.

Reading JSON From a File or String in PHP

Let's say you have a file which contains information in JSON format. How do you access and store it in PHP?

First, you need to get the data from the file into a variable by using file_get_contents(). Once the data is in a string, you can call the json_decode() function to extract information from the string. Keep in mind that JSON simply provides a way to store information as a string using a set of predefined rules. It is our job to decode the strings properly and get the information we want.

The json_decode() function accepts four parameters, but you will only need the first two in most situations. The first parameter specifies the string that you want to decode. The second parameter determines how the decoded data is returned. Setting it to true will return an associative array, and false will return objects. Here is a basic example. We have a file called people.json with the following contents:

1
{
2
    "name": "Monty",
3
    "email": "monty@something.com",
4
    "age": 77
5
}

We can read information from this JSON file by using the code below:

1
<?php
2
3
$people_json = file_get_contents('people.json');
4
5
$decoded_json = json_decode($people_json, false);
6
7
echo $decoded_json->name;
8
// Monty

9
10
echo $decoded_json->email;
11
// monty@something.com

12
13
echo $decoded_json->age;
14
// 77

15
16
?>

In the above example, json_decode() returned an object because the second parameter was set to false. You can set it to true to get the data back as an associative array.

1
<?php
2
3
$people_json = file_get_contents('people.json');
4
5
$decoded_json = json_decode($people_json, true);
6
7
echo $decoded_json['name'];
8
// Monty

9
10
echo $decoded_json['email'];
11
// monty@something.com

12
13
echo $decoded_json['age'];
14
// 77

15
16
?>

Now, we will decode JSON that is slightly more complicated and try to get back useful information from it.

1
{
2
    "name": "Monty",
3
    "email": "monty@something.com",
4
    "age": 77,
5
    "countries": [
6
        {"name": "Spain", "year": 1982},
7
        {"name": "Australia", "year": 1996},
8
        {"name": "Germany", "year": 1987}
9
    ]
10
}

Our goal is to get back all the countries visited by the person in different years. The value returned by $decoded_json['countries'] will actually be an array, and we will loop through it like regular arrays to get our data.

1
<?php
2
3
$people_json = file_get_contents('people.json');
4
5
$decoded_json = json_decode($people_json, true);
6
7
$name = $decoded_json['name'];
8
$countries = $decoded_json['countries'];
9
10
foreach($countries as $country) {
11
    echo $name.' visited '.$country['name'].' in '.$country['year'].'.';
12
}
13
/*

14
Monty visited Spain in 1982.

15
Monty visited Australia in 1996.

16
Monty visited Germany in 1987.

17
*/
18
19
?>

Let's go over just one last example of extracting information from a JSON file. Here is the JSON from which we will extract our data.

1
{
2
    "customers": [
3
      {
4
        "name": "Andrew",
5
        "email": "andrew@something.com",
6
        "age": 62,
7
        "countries": [
8
          {
9
            "name": "Italy",
10
            "year": 1983
11
          },
12
          {
13
            "name": "Canada",
14
            "year": 1998
15
          },
16
          {
17
            "name": "Germany",
18
            "year": 2003
19
          }
20
        ]
21
      },
22
      {
23
        "name": "Sajal",
24
        "email": "sajal@something.com",
25
        "age": 65,
26
        "countries": [
27
          {
28
            "name": "Belgium",
29
            "year": 1994
30
          },
31
          {
32
            "name": "Hungary",
33
            "year": 2001
34
          },
35
          {
36
            "name": "Chile",
37
            "year": 2013
38
          }
39
        ]
40
      },
41
      {
42
        "name": "Adam",
43
        "email": "adam@something.com",
44
        "age": 72,
45
        "countries": [
46
          {
47
            "name": "France",
48
            "year": 1988
49
          },
50
          {
51
            "name": "Brazil",
52
            "year": 1998
53
          },
54
          {
55
            "name": "Poland",
56
            "year": 2002
57
          }
58
        ]
59
      },
60
      {
61
        "name": "Monty",
62
        "email": "monty@something.com",
63
        "age": 77,
64
        "countries": [
65
          {
66
            "name": "Spain",
67
            "year": 1982
68
          },
69
          {
70
            "name": "Australia",
71
            "year": 1996
72
          },
73
          {
74
            "name": "Germany",
75
            "year": 1987
76
          }
77
        ]
78
      }
79
    ]
80
}

We have two nested arrays in the JSON data this time. So we will be using two nested loops to get the countries visited by different customers.

1
<?php
2
3
$people_json = file_get_contents('people.json');
4
5
$decoded_json = json_decode($people_json, true);
6
7
$customers = $decoded_json['customers'];
8
9
foreach($customers as $customer) {
10
    $name = $customer['name'];
11
    $countries = $customer['countries'];
12
13
    foreach($countries as $country) {
14
        echo $name.' visited '.$country['name'].' in '.$country['year'].'.';
15
    }
16
}
17
18
/*

19
Andrew visited Italy in 1983.

20
Andrew visited Canada in 1998.

21
Andrew visited Germany in 2003.

22


23
Sajal visited Belgium in 1994.

24
Sajal visited Hungary in 2001.

25
Sajal visited Chile in 2013.

26


27
Adam visited France in 1988.

28
Adam visited Brazil in 1998.

29
Adam visited Poland in 2002.

30


31
Monty visited Spain in 1982.

32
Monty visited Australia in 1996.

33
Monty visited Germany in 1987.

34
*/
35
36
?>

You should now have a rough idea of the approach you should take to read JSON data from a file depending on how it has been created.

Reading JSON Data Without Knowing the Keys Beforehand

So far we have read JSON data where we already knew all the keys. That might not always be true. Luckily, we can still extract useful information from the file once we have stored it as an associative array. The following example should clear things up.

1
{
2
    "kdsvhe": {
3
        "name": "Andrew",
4
        "age": 62
5
    },
6
    "lvnwfd": {
7
        "name": "Adam",
8
        "age": 65
9
    },
10
    "ewrhbw": {
11
        "name": "Sajal",
12
        "age": 72
13
    },
14
    "klkwcn": {
15
        "name": "Monty",
16
        "age": 77
17
    }
18
}

The keys in the above JSON seem to be random strings that we cannot predict beforehand. However, once we convert it into an associative array, we will no longer need to know the exact key values to iterate through the data.

1
<?php
2
3
$people_json = file_get_contents('people.json');
4
5
$decoded_json = json_decode($people_json, true);
6
7
foreach($decoded_json as $key => $value) {
8
    $name = $decoded_json[$key]["name"];
9
    $age = $decoded_json[$key]["age"];
10
    
11
    echo $name.' is '.$age.' years old.';
12
}
13
14
/*

15
Andrew is 62 years old.

16
Adam is 65 years old.

17
Sajal is 72 years old.

18
Monty is 77 years old.

19
*/
20
21
?>

Creating JSON Data in PHP

You can also turn your own data into a well-formatted JSON string in PHP with the help of the json_encode() function. It basically accepts three parameters, but you will usually only need the first one, i.e. the value you want to encode in most situations.

1
<?php
2
3
$people_info = [
4
    "customers" => [
5
        ["name" => "Andrew", "score" => 62.5],
6
        ["name" => "Adam", "score" => 65.0],
7
        ["name" => "Sajal", "score" => 72.2],
8
        ["name" => "Monty", "score" => 57.8]
9
    ]
10
];
11
12
echo json_encode($people_info);
13
14
/*

15
{"customers":[{"name":"Andrew","score":62.5},{"name":"Adam","score":65},{"name":"Sajal","score":72.2},{"name":"Monty","score":57.8}]}

16
*/
17
18
?>

You might also need to use some flags in order to get the JSON string in the desired format. For example, you can use the JSON_PRETTY_PRINT flag to add white space for proper formatting of the JSON string. Similarly, you can use the JSON_PRESERVE_ZERO_FRACTION flag to make sure float values are always stored as floats, even if they are equivalent to some integer in magnitude. You can see a list of all such flags in the official documentation.

1
<?php
2
3
$people_info = [
4
    "customers" => [
5
        ["name" => "Andrew", "score" => 62.5],
6
        ["name" => "Adam", "score" => 65.0],
7
        ["name" => "Sajal", "score" => 72.2],
8
        ["name" => "Monty", "score" => 57.8]
9
    ]
10
];
11
12
echo json_encode($people_info, JSON_PRETTY_PRINT|JSON_PRESERVE_ZERO_FRACTION);
13
14
/*

15
{

16
    "customers": [

17
        {

18
            "name": "Andrew",

19
            "score": 62.5

20
        },

21
        {

22
            "name": "Adam",

23
            "score": 65.0

24
        },

25
        {

26
            "name": "Sajal",

27
            "score": 72.2

28
        },

29
        {

30
            "name": "Monty",

31
            "score": 57.8

32
        }

33
    ]

34
}

35
*/
36
37
?>

Dealing With Errors During Encoding and Decoding

The JSON format requires us to follow a specific set of rules for proper encoding and decoding of the strings. For example, names and values should be enclosed in double quotes, and there should be no trailing comma after name-value pairs. The json_last_error_msg() function can help you figure out what kind of error you are getting so that you can take appropriate steps. Here is a very basic example:

1
<?php
2
3
$sample_json = '{"name": "value", }';
4
5
var_dump(json_decode($sample_json));
6
// NULL

7
8
echo json_last_error_msg();
9
// Syntax error

10
11
?>

Final Thoughts

In this tutorial, you learned how to read JSON data from a file or string in PHP. You also learned how to convert that JSON into an array and traverse it to extract the information you want. You should now be able to get information from JSON in a file where you don't know all the keys in key-value pairs.

In the last two sections, we covered how you can stringify data as JSON in PHP and the errors you might encounter during the encoding and decoding process.

Hopefully, this will answer all your questions about encoding and decoding JSON in PHP.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.