PHP json_encode() Function
The PHP json_encode() function returns a string containing the JSON representation of the given value.
The encoding is affected by the supplied flags and additionally the encoding of float values depends on the value of serialize_precision.
Syntax
json_encode(value, flags, depth)
Parameters
value |
Required. Specify the value being encoded. Can be of any type except a resource. All string data must be UTF-8 encoded. |
flags |
Optional. Specify Bitmask consisting of 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. The behavior of these constants is described on the JSON constants page. |
depth |
Optional. Specify the maximum depth. Must be greater than zero. Default is 512. |
Return Value
Returns a JSON encoded string on success or false on failure.
Example: json_encode() example
The example below shows how to use the json_encode() function with a PHP array.
<?php //declaring an array $arr = array('a' => 10, 'b' => 20, 'c' => 30); //using json_encode() function to //encode into JSON string $jsonObj = json_encode($arr); //displaying the result echo $jsonObj; ?>
The output of the above code will be:
{"a":10,"b":20,"c":30}
Example: json_encode() example with PHP object
The example below shows how to use this function with a PHP object.
<?php //declaring a class class person { } //declaring an object $p1 = new person(); //setting the object elements $p1->name = "John"; $p1->email = "john@example.com"; //using json_encode() function to //encode into JSON string $jsonObj = json_encode($p1); //displaying the result echo $jsonObj; ?>
The output of the above code will be:
{"name":"John","email":"john@example.com"}
Example: using flag parameter
Consider one more example which illustrates on using JSON_PRESERVE_ZERO_FRACTION option with this function.
<?php var_dump(json_encode(12.0, JSON_PRESERVE_ZERO_FRACTION)); var_dump(json_encode(12.0)); ?>
The output of the above code will be:
string(4) "12.0" string(2) "12"
❮ PHP JSON Reference