How do I encode a PHP object into JSON string?

To encode objects into a JSON formatted string in PHP, you can use the json_encode(value, options, depth) function. The first parameter specifies the PHP object to encode. You can control how the PHP object will be encoded into JSON by passing a combination of bitmasks in the second parameter. See the list of supported bitmasks for the JSON encoder below. The third optional parameter specifies the maximum recursion depth, in other words, how deep the encoding function will go through the nested PHP objects and convert them to JSON. In this PHP Encode JSON example, we use the json_encode() function to encode a PHP object into a JSON representation. Click Execute to run the PHP JSON Encode Example online and see the result.
How do I encode a PHP object into JSON string? Execute
<?php
$json = array(
  'Leo' => 35,
  'Alice' => 37,
  'Dora' => 43
);

echo json_encode($json);
?>
Updated: Viewed: 1297 times

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 many programming languages, including PHP, JavaScript, Java, C++, C#, Go, Python, and many more.JSON file names use the .json file extension.

PHP JSON Encode Function Syntax

To convert a PHP array or object to a JSON representation, you can use the json_encode() function:

PHP json_encode() Syntax
json_encode(value, options, depth)

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 decode function supports the following bitmasks: JSON_FORCE_OBJECT, JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_NUMERIC_CHECK, JSON_PARTIAL_OUTPUT_ON_ERROR, JSON_PRESERVE_ZERO_FRACTION, JSON_PRETTY_PRINT, JSON_UNESCAPED_LINE_TERMINATORS, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, JSON_THROW_ON_ERROR. 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() Example
<?php
$json = array(
  'Leo' => 35,
  'Alice' => 37,
  'Dora' => 43
);

echo json_encode($json);
?>

#output: {"Leo":35,"Alice":37,"Dora":43}

See also