What is PHP?
PHP is a server-side scripting language that is widely used for web development programming. It can be embedded into HTML and executed on the server side to create dynamic web pages and web-based applications. PHP has a large developer community, extensive documentation, and many open-source projects, making it easy for developers to learn and use. PHP is cross-platform and can run on various operating systems like Linux, Windows, and macOS.
What is JSON?
How to decode JSON in PHP?
In PHP, the json_decode() function is used to decode JSON strings into PHP objects. The result object can be any PHP data type except for resource pointers such as a database or file descriptor. Following is the syntax of the json_decode() function:
- string: specifies the value to be decoded. It only works with UTF-8 encoded strings.
- assoc (Optional): specifies a boolean value. If set to "true", the returned object will be converted to an associative array. If set to "false", it returns an object. The default value is "false".
- depth (Optional): specifies the recursion depth. The default JSON decoding recursion depth is 512.
- options (Optional): specifies a bitmask that determines how JSON objects will be converted to PHP objects. The decode function supports the following bitmasks: JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR. You can learn more about JSON decoding bitmasks in the PHP documentation.
PHP JSON Decode Function Examples
The following are examples of using the json_decode() function in PHP:
Decoding JSON string
The following is an example of decoding a JSON string into an object using json_decode():
Decoding JSON array
The following is an example of decoding a JSON array into an object using json_decode():
Decoding a JSON containing nested objects
The following is an example of decoding JSON containing nested objects into a PHP object using json_decode():
How to encode PHP object to JSON string?
To encode a PHP object to JSON string, you can use the json_encode() function.