JavaScript Object Notation or JSON is a simple data-interchange format that is created openly. Today a lot of applications use JSON to transfer data between server and client. As a server-side programming language PHP provides JSON-related functions. In order to encode a JSON data the json_encode() function is provided by PHP. PHP uses the array data type as the main container for JSON objects so the json_encode() function will accept an array with different types of items to convert.
json_encode() Syntax
The json_encode() method has the following syntax where 3 parameters can be specified but only 1 parameter is required and the other 2 parameters are optional.
json_encode(VALUE,OPTIONS,DEPTH)
- VALUE is the PHP array variable which is the source of the JSON data. This parameter is required.
- OPTIONS provides different options during encoding. This parameter is optional.
- DEPTH specifies the maximum depth where the JSON data should be read from the given PHP VALUE which is an array. This parameter is optional.
For the OPTIONS parameter following bitmask can be specified.
JSON_FORCE_OBJECT, JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_NUMERIC_CHECK, JSON_PARTIAL_OUTPUT_ON_ERROR, JSON_PRESERVE_ZERO_FRACTION, JSON_PRETTY_PRINT, JSON_UNESCAPED_LINE_TERMINATORS, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, JSON_THROW_ON_ERROR
Encode JSON
In order to encode into JSON and create JSON data, we will first define an array that will contain the JSON values. We will use the array named $persons which contains a named array with key and value pairs.
<?php
$persons = array("ismail"=>36,"ahmet"=>7,"elif"=>11);
json_data = json_encode($persons);
print($json_data);
?>
The content of the $json_data will be like below which is in JSON format where the data is surrounded with curly brackets, keys and values are paired with a double colon.
{"ismail":36,"ahmet":7,"elif":11}
Encode Multi-Level JSON
In real life, there will be more complex scenarios for the JSON data. The PHP array can be a multilevel array with a parent and child relationship. The array will contain items that are arrayed too.
<?php
$persons = array("ismail"=>array("surname"=>"baydan","age"=>36),
"ahmet"=>array("surname"=>"baydan","age"=>7),
"elif"=>array("surname"=>"baydan","age"=>11));
$json_data = json_encode($persons);
print($json_data);
?>
The output will be like the below which is in JSON format. We see that a JSON item has sub-values as key/value pairs. For example, the “ismail” key has a JSON that contains the “surname” and “age” keys.
{ "ismail":{ "surname":"baydan", "age":36 }, "ahmet":{ "surname":"baydan", "age":7 }, "elif":{ "surname":"baydan", "age":11 } }