What is PHP?
PHP is a server-side scripting language that is widely used for web development. It can be embedded into HTML and executed on the server side to create dynamic web pages and web-based applications. One of the significant advantages of PHP is its large community support and extensive documentation, which makes it easy for developers to learn and use. Additionally, PHP is cross-platform compatible and can run on various operating systems like Linux, Windows, and macOS.
What is JSON?
JSON (JavaScript Object Notation) is a standard text-based data interchange format that is based on the JavaScript object syntax. JSON is widely used for data exchange between applications written in many programming languages, including JavaScript, PHP, Java, C++, C#, Go, Python, and many more.
How to decode JSON in PHP?
In PHP, the json_decode() function is used to decode a JSON string into a PHP object. 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:
Where:
- 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 decodeding 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
How to encode PHP object to JSON string?
To encode a PHP object to JSON string, you can use the json_encode() function.