What is PHP?
What is JSON?
How to encode an object into a JSON string in PHP?
To convert a PHP array or object to a JSON representation, you can use the json_encode() function:
- value: required parameter, specifies the value to encode
- options (Optional): specifies a bitmask that determines how JSON objects will be converted to PHP objects. The encode function supports the following bitmasks: JSON_FORCE_OBJECT, JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, etc. You can learn more about JSON encoding bitmasks in the PHP documentation.
- depth (Optional): defines the maximum depth. The value must be greater than zero
PHP JSON Encode Examples
The following are examples of using json_encode() function in PHP:
Encoding an associative array to JSON
The following is an example of encoding an associative array to JSON using the json_encode() function:
Encoding multidimensional array to JSON
The following is an example of encoding a multidimensional array to JSON using the json_encode() function:
Encoding an object to JSON
The following is an example of encoding an object to JSON using the json_encode() function:
Encoding an UTF-8 string to JSON
The following is an example of encoding a UTF-8 string to JSON using the json_encode() function:
How to decode JSON string into PHP object?
To decode a JSON string back into a PHP object, you can use the json_decode() function. The result object can be any PHP data type, including an array, except resource pointers such as a database or file descriptor.