How to Encode and Decode JSON Data in PHP
![](https://plantpot.works/wp-content/uploads/2021/09/5918.png)
Contents
In this article, you will learn how to encode and decode JSON data in PHP.
PHP JSON Functions
In PHP, you can use the built-in functions json_encode and json_decode to work with JSON data.
PHP json_encode() Function
The json_encode() function is used to convert a PHP variable (e.g. an array or object) into a JSON string.
For example:
<?php
$data = array("name" => "John", "age" => 30);
$json = json_encode($data);
?>
This function has an optional second parameter that allows you to customize the behavior of the encoding process. For example, you can use the JSON_PRETTY_PRINT option to format the JSON string with whitespace and indentation, making it more human-readable:
<?php
$json = json_encode($data, JSON_PRETTY_PRINT);
?>
PHP json_decode() Function
The json_decode() function is used to convert a JSON string into a PHP variable.
For example:
<?php
$json = '{"name":"John", "age":30}';
$data = json_decode($json);
?>
You can also use the json_decode() function with the second parameter as true to convert json to associative array:
<?php
$json = '{"name":"John", "age":30}';
$data = json_decode($json, true);
?>
This function also has an optional second parameter that allows you to specify the data type of the returned value. By default, it returns a stdClass object, but you can set it to return an associative array by passing true as the second parameter:
<?php
$data = json_decode($json, true);
?>
You can also use the third parameter which is used to specify options. The JSON_BIGINT_AS_STRING option will return large integers as strings instead of floats. This can help to avoid precision loss when working with large integers.
<?php
$data = json_decode($json, false, 512);
?>
The json_last_error() function returns the last error occurred. You can use this function to check for errors when decoding or encoding JSON data:
<?php
$json = json_encode($data);
if (json_last_error() !== JSON_ERROR_NONE) {
echo "JSON encoding failed: " . json_last_error_msg();
}
?>
The json_last_error_msg() function returns the error message of last json error.
You can also specify options to control encoding and decoding process. You can find more details in the official documentation at:
https://www.php.net/manual/en/book.json.php