Cara menggunakan can php read json?

Pada ReST, seringkali kita menggunakan format JSON atau XML untuk melakukan representasi record pada database.

Pada saat menggunakan format JSON dalam PHP, saya memiliki kasus sebuah array yang memiliki key default, seperti ini:

<?php

$default = array('Spirit', 'Walk', 'Run', 'Jump');

?>

Array Key tersebut secara default tentu akan sama seperti ini:

<?php

$default = array(0 => 'Spirit', 1 => 'Walk', 2 => 'Run', 3 => 'Jump');

?>

Permasalahannya adalah ketika array tersebut di encode kedalam format JSON menggunakan function json_encode(), array key tersebut “hilang”, menjadi seperti ini:

["Spirit","Walk","Run","Jump"]

Salah satu solusinya agar array key tersebut bisa “dibawa” kedalam format JSON, array tersebut harus berbentuk object, dengan menambahkan konstanta JSON_FORCE_OBJECT sebagai parameter function json_encode(), menjadi:

<?php

$encode = json_encode($default, JSON_FORCE_OBJECT);

?>

Sehingga menghasilkan:

{"0":"Spirit","1":"Walk","2":"Run","3":"Jump"}

Dengan menjadikannya object, array key tersebut akan “dibawa” dalam format JSON. 😀

Lalu untuk melakukan proses decode format JSON object tersebut ke dalam bentuk array, gunakan paramater TRUE pada function json_decode(), seperti ini:

Here is a JavaScript on the client, using an AJAX call to request the PHP file from the example above:

Example

Use JSON.parse() to convert the result into a JavaScript object:

const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  document.getElementById("demo").innerHTML = myObj.name;
}
xmlhttp.open("GET", "demo_file.php");
xmlhttp.send();

Try it Yourself »



PHP Array

Arrays in PHP will also be converted into JSON when using the PHP function json_encode():

PHP file

$myArr = array("John", "Mary", "Peter", "Sally");

$myJSON = json_encode($myArr);

echo $myJSON;
?>

Show PHP file »

The Client JavaScript

Here is a JavaScript on the client, using an AJAX call to request the PHP file from the array example above:

Example

Use JSON.parse() to convert the result into a JavaScript array:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  document.getElementById("demo").innerHTML = myObj[2];
}
xmlhttp.open("GET", "demo_file_array.php", true);
xmlhttp.send();

Try it Yourself »


PHP Database

PHP is a server side programming language, and can be used to access a database.

Imagine you have a database on your server, and you want to send a request to it from the client where you ask for the 10 first rows in a table called "customers".

On the client, make a JSON object that describes the numbers of rows you want to return.

Before you send the request to the server, convert the JSON object into a string and send it as a parameter to the url of the PHP page:

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

    "email": "[email protected]",
33 and
    "email": "[email protected]",
34 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

    "email": "[email protected]",
35. Once the data is in a string, you can call the
    "email": "[email protected]",
36 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

    "email": "[email protected]",
33 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
    "email": "[email protected]",
38 will return an associative array, and
    "email": "[email protected]",
39 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": "[email protected]",
4
    "age": 77
5
}

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

1
{
1
2
3
{
4
4
5
{
7
{
8
{
9
2
0
2
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
    "name": "Monty",
0
    "name": "Monty",
1
    "name": "Monty",
2
    "name": "Monty",
3
    "name": "Monty",
4
    "name": "Monty",
5

In the above example,

    "email": "[email protected]",
33 returned an object because the second parameter was set to
    "email": "[email protected]",
39. You can set it to
    "email": "[email protected]",
38 to get the data back as an associative array.

1
{
1
2
3
{
4
4
5
3
3
{
8
{
9
3
6
2
1
2
2
2
3
2
4
    "email": "[email protected]",
1
2
6
2
7
2
8
2
9
    "email": "[email protected]",
6
    "name": "Monty",
1
    "name": "Monty",
2
    "name": "Monty",
3
    "name": "Monty",
4
    "name": "Monty",
5

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": "[email protected]",
4
4
9
5
    "age": 77
1
{
8
    "age": 77
3
{
9
    "age": 77
5
2
1
    "age": 77
7
2
3
    "age": 77
9
2
4
}

Our goal is to get back all the countries visited by the person in different years. The value returned by

    "email": "[email protected]",
43 will actually be an array, and we will loop through it like regular arrays to get our data.

1
{
1
2
3
{
4
4
5
3
3
{
8
{
9
}
2
2
1
}
4
2
3
2
4
}
7
2
6
}
9
2
8
{
01
2
9
{
03
    "name": "Monty",
1
{
05
    "name": "Monty",
3
{
07
    "name": "Monty",
4
{
09
{
10
{
11
{
12
{
13
    "name": "Monty",
5

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
{
18
3
{
20
4
{
22
5
{
24
{
8
{
26
{
9
{
28
2
1
{
30
2
3
{
32
2
4
{
34
2
6
{
36
2
8
{
30
2
9
{
40
    "name": "Monty",
1
{
42
    "name": "Monty",
3
{
36
    "name": "Monty",
4
{
30
{
10
{
48
{
12
{
50
{
13
{
52
{
53
{
54
{
55
{
56
{
57
{
20
{
59
{
60
{
61
{
62
{
63
{
64
{
65
{
28
{
67
{
30
{
69
{
70
{
71
{
72
{
73
{
36
{
75
{
30
{
77
{
78
{
79
{
80
{
81
{
36
{
83
{
30
{
85
{
86
{
87
{
88
{
89
{
52
{
91
{
54
{
93
{
56
{
95
{
20
{
97
{
98
{
99
2
00
2
01
2
02
2
03
{
28
2
05
{
30
2
07
2
08
2
09
2
10
2
11
{
36
2
13
{
30
2
15
2
16
2
17
{
42
2
19
{
36
2
21
{
30
2
23
2
24
2
25
2
26
2
27
{
52
2
29
{
54
2
31
{
56
2
33
{
20
2
35
2
36
2
37
2
38
2
39
2
40
2
41
{
28
2
43
{
30
2
45
2
46
2
47
2
48
2
49
{
36
2
51
{
30
2
53
2
54
2
55
2
56
2
57
{
36
2
59
{
30
2
61
{
48
2
63
2
64
2
65
{
52
2
67
{
54
2
69
2
70
2
71
    "age": 77
9
2
73
}

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
{
1
2
3
{
4
4
5
3
3
{
8
{
9
2
85
2
1
2
3
2
88
2
4
2
90
2
6
2
92
2
8
2
9
2
95
    "name": "Monty",
1
2
97
    "name": "Monty",
3
2
99
    "name": "Monty",
4
{
01
{
10
{
12
{
03
{
13
    "name": "Monty",
06
{
53
    "name": "Monty",
08
{
55
    "name": "Monty",
10
{
57
    "name": "Monty",
12
{
59
    "name": "Monty",
14
{
61
    "name": "Monty",
16
{
63
    "name": "Monty",
18
{
65
    "name": "Monty",
12
{
67
    "name": "Monty",
22
{
69
    "name": "Monty",
24
{
71
    "name": "Monty",
26
{
73
    "name": "Monty",
12
{
75
{
05
{
77
{
07
{
79
{
09
{
81
{
11
{
83
{
85
    "name": "Monty",
5

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
    "name": "Monty",
43
3
{
22
4
    "name": "Monty",
47
5
    "name": "Monty",
49
{
8
    "name": "Monty",
51
{
9
{
98
2
1
    "name": "Monty",
55
2
3
    "name": "Monty",
49
2
4
    "name": "Monty",
59
2
6
{
60
2
8
    "name": "Monty",
63
2
9
    "name": "Monty",
49
    "name": "Monty",
1
    "name": "Monty",
67
    "name": "Monty",
3
2
36
    "name": "Monty",
4
    "name": "Monty",
71
{
10
    "name": "Monty",
73
{
12
}

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
{
1
2
3
{
4
4
5
3
3
{
8
{
9
    "name": "Monty",
86
2
1
    "name": "Monty",
88
2
3
    "name": "Monty",
90
2
4
    "name": "Monty",
92
2
6
    "name": "Monty",
94
2
8
{
01
2
9
    "name": "Monty",
1
{
03
    "name": "Monty",
3
3
01
    "name": "Monty",
4
3
03
{
10
3
05
{
12
3
07
{
13
{
11
{
53
{
55
    "name": "Monty",
5

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

    "email": "[email protected]",
44 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
{
1
2
3
3
17
4
3
19
5
3
21
{
8
3
23
{
9
3
25
2
1
3
27
2
3
3
29
2
4
3
31
2
6
2
8
3
34
2
9
    "name": "Monty",
1
{
03
    "name": "Monty",
3
3
39
    "name": "Monty",
4
{
11
{
10
{
12
    "name": "Monty",
5

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

    "email": "[email protected]",
45 flag to add white space for proper formatting of the JSON string. Similarly, you can use the
    "email": "[email protected]",
46 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
{
1
2
3
3
17
4
3
19
5
3
21
{
8
3
23
{
9
3
25
2
1
3
27
2
3
3
29
2
4
3
31
2
6
2
8
3
66
2
9
    "name": "Monty",
1
{
03
    "name": "Monty",
3
3
71
    "name": "Monty",
4
3
73
{
10
3
75
{
12
3
77
{
13
3
79
{
53
3
81
{
55
3
75
{
57
3
85
{
59
3
87
{
61
3
81
{
63
3
75
{
65
3
93
{
67
3
95
{
69
3
81
{
71
3
75
{
73
    "email": "[email protected]",
01
{
75
    "email": "[email protected]",
03
{
77
    "email": "[email protected]",
05
{
79
    "email": "[email protected]",
07
{
81
    "email": "[email protected]",
09
{
83
{
11
{
85
{
87
    "name": "Monty",
5

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

    "email": "[email protected]",
47 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
{
1
2
3
    "email": "[email protected]",
19
4
5
    "email": "[email protected]",
22
{
8
    "email": "[email protected]",
24
{
9
2
1
    "email": "[email protected]",
27
2
3
    "email": "[email protected]",
29
2
4
2
6
    "name": "Monty",
5

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.