Pada ReST, seringkali kita menggunakan format JSON atau XML untuk melakukan representasi record pada database. Show 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: ExampleUse JSON.parse() to convert the result into a JavaScript object: const xmlhttp = new XMLHttpRequest(); PHP ArrayArrays 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; The Client JavaScriptHere is a JavaScript on the client, using an AJAX call to request the PHP file from the array example above: ExampleUse JSON.parse() to convert the result into a JavaScript array: var xmlhttp = new XMLHttpRequest(); PHP DatabasePHP 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 PHPLet'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 20 21 22 23 24 25 26 27 28 29 "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 33 {8 {9 36 21 22 23 24 "email": "[email protected]",1 26 27 28 29 "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 49 5 "age": 771 {8 "age": 773 {9 "age": 775 21 "age": 777 23 "age": 779 24 } 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 33 {8 {9 }2 21 }4 23 24 }7 26 }9 28 {01 29 {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 21 {30 23 {32 24 {34 26 {36 28 {30 29 {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 200 201 202 203 {28 205 {30 207 208 209 210 211 {36 213 {30 215 216 217 {42 219 {36 221 {30 223 224 225 226 227 {52 229 {54 231 {56 233 {20 235 236 237 238 239 240 241 {28 243 {30 245 246 247 248 249 {36 251 {30 253 254 255 256 257 {36 259 {30 261 {48 263 264 265 {52 267 {54 269 270 271 "age": 779 273 } 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 33 {8 {9 285 21 23 288 24 290 26 292 28 29 295 "name": "Monty",1 297 "name": "Monty",3 299 "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 BeforehandSo 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 21 "name": "Monty",55 23 "name": "Monty",49 24 "name": "Monty",59 26 {60 28 "name": "Monty",63 29 "name": "Monty",49 "name": "Monty",1 "name": "Monty",67 "name": "Monty",3 236 "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 33 {8 {9 "name": "Monty",86 21 "name": "Monty",88 23 "name": "Monty",90 24 "name": "Monty",92 26 "name": "Monty",94 28 {01 29 "name": "Monty",1 {03 "name": "Monty",3 301 "name": "Monty",4 303 {10 305 {12 307 {13 {11 {53 {55 "name": "Monty",5 Creating JSON Data in PHPYou 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 317 4 319 5 321 {8 323 {9 325 21 327 23 329 24 331 26 28 334 29 "name": "Monty",1 {03 "name": "Monty",3 339 "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 317 4 319 5 321 {8 323 {9 325 21 327 23 329 24 331 26 28 366 29 "name": "Monty",1 {03 "name": "Monty",3 371 "name": "Monty",4 373 {10 375 {12 377 {13 379 {53 381 {55 375 {57 385 {59 387 {61 381 {63 375 {65 393 {67 395 {69 381 {71 375 {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 DecodingThe 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 21 "email": "[email protected]",27 23 "email": "[email protected]",29 24 26 "name": "Monty",5 Final ThoughtsIn 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. |