PHP JSON Functions: json_encode() & json_decode()

The json_encode() function converts a PHP variable into a JSON formatted string. It takes one parameter, the PHP variable to be converted. If successful, it will return a JSON formatted string; otherwise, it will return false.

Here are some common usage examples:

  1. Convert the array to a JSON string.
$data = array('name' => 'John', 'age' => 30);
$jsonString = json_encode($data);
echo $jsonString;

The output result is: {“name”:”John”,”age”:30}

  1. Convert the object into a JSON string.
class Person {
    public $name;
    public $age;
}

$person = new Person();
$person->name = 'John';
$person->age = 30;

$jsonString = json_encode($person);
echo $jsonString;

The output will be: {“name”: “John”, “age”: 30}

  1. You can specify the depth that needs to be encoded through the second parameter.
$data = array('name' => 'John', 'age' => 30);
$jsonString = json_encode($data, JSON_PRETTY_PRINT);
echo $jsonString;

The output is:

{
    "name": "John",
    "age": 30
}

The json_decode() function is used to convert a JSON formatted string into a PHP variable. It takes one parameter, which is the JSON string to be converted. If successful, it will return a PHP variable; otherwise it will return null.

Here are some common usage examples:

  1. Convert a JSON string to an array.
$jsonString = '{"name":"John","age":30}';
$data = json_decode($jsonString, true);
print_r($data);

The output result is: Array([name] => John [age] => 30)

  1. Convert a JSON string into an object.
$jsonString = '{"name":"John","age":30}';
$data = json_decode($jsonString);
echo $data->name;
echo $data->age;

The output is: John 30

  1. You can specify the type of data to return with the second parameter.
$jsonString = '{"name":"John","age":30}';
$data = json_decode($jsonString, false, 512, JSON_BIGINT_AS_STRING);
print_r($data);

The output result is: stdClass Object([name] => John [age] => 30)

It is important to note that the json_decode() function by default returns a stdClass object, to return an array instead, the second parameter needs to be set to true.

Additionally, the json_decode() function has some optional parameters, such as the third parameter which can be used to specify the maximum decoding depth, and the fourth parameter which can be used to specify options to be used during decoding. For more information, please refer to the PHP official documentation.

bannerAds