What is PHP?
PHP is a general-purpose server-side programming language for web development. PHP integrates with many web development technologies, such as HTML, CSS, JavaScript, and SQL. PHP can run on many operating systems, including Windows, Linux, and macOS, and supports multiple databases such as MySQL, PostgreSQL, and SQLite.
What is JSON?
JavaScript Object Notation (JSON) is a textual format for representing structured data based on the syntax of a JavaScript object. JSON is widely used for data exchange between applications written in different programming languages, including PHP, JavaScript, Java, C++, C#, Go, Python, and many more. JSON file names use the .json file extension.
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:
Where:
- 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.