The [json_encode](<http://php.net/manual/en/function.json-encode.php>)
function will convert a PHP array (or, since PHP 5.4, an object which implements the JsonSerializable
interface) to a JSON-encoded string. It returns a JSON-encoded string on success or FALSE on failure.
$array = [
'name' => 'Jeff',
'age' => 20,
'active' => true,
'colors' => ['red', 'blue'],
'values' => [0=>'foo', 3=>'bar'],
];
During encoding, the PHP data types string, integer, and boolean are converted to their JSON equivalent. Associative arrays are encoded as JSON objects, and – when called with default arguments – indexed arrays are encoded as JSON arrays. (Unless the array keys are not a continuous numeric sequence starting from 0, in which case the array will be encoded as a JSON object.)
echo json_encode($array);
Output:
{"name":"Jeff","age":20,"active":true,"colors":["red","blue"],"values":{"0":"foo","3":"bar"}}
Since PHP 5.3, the second argument to json_encode
is a bitmask which can be one or more of the following.
As with any bitmask, they can be combined with the binary OR operator |
.
[JSON_FORCE_OBJECT](<http://php.net/manual/en/json.constants.php#constant.json-force-object>)
Forces the creation of an object instead of an array
$array = ['Joel', 23, true, ['red', 'blue']];
echo json_encode($array);
echo json_encode($array, JSON_FORCE_OBJECT);
Output:
["Joel",23,true,["red","blue"]]
{"0":"Joel","1":23,"2":true,"3":{"0":"red","1":"blue"}}
[JSON_HEX_TAG](<http://php.net/manual/en/json.constants.php#constant.json-hex-tag>)
, [JSON_HEX_AMP](<http://php.net/manual/en/json.constants.php#constant.json-hex-amp>)
, [JSON_HEX_APOS](<http://php.net/manual/en/json.constants.php#constant.json-hex-apos>)
, [JSON_HEX_QUOT](<http://php.net/manual/en/json.constants.php#constant.json-hex-quot>)
Ensures the following conversions during encoding:
Constant | Input | Output | —| — | — |
|JSON_HEX_TAG
| \\<
| \\u003C
| |JSON_HEX_TAG
| \\>
| \\u003E
| |JSON_HEX_AMP
| &
| \\u0026
| |JSON_HEX_APOS
| \\'
| \\u0027
| |JSON_HEX_QUOT
| "
| \\u0022
|
$array = ["tag"=>"<>", "amp"=>"&", "apos"=>"'", "quot"=>"\\""];
echo json_encode($array);
echo json_encode($array, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);