The json_encode Function
The json_encode
function converts PHP variables (arrays, objects, strings, numbers) into a JSON format string. Its first parameter accepts the value to be encoded, the second (optional) - flags for configuring the encoding process, the third - the transformation depth.
Syntax
json_encode(mixed $value, [int $flags = 0], [int $depth = 512]): string|false
Example
Let's convert a simple array to JSON:
<?php
$arr = [1, 2, 3, 4, 5];
echo json_encode($arr);
?>
Code execution result:
'[1,2,3,4,5]'
Example
Let's convert an associative array to JSON:
<?php
$arr = ['a' => 1, 'b' => 2, 'c' => 3];
echo json_encode($arr);
?>
Code execution result:
'{"a":1,"b":2,"c":3}'
Example
Using the JSON_PRETTY_PRINT
flag for pretty formatting:
<?php
$arr = ['a' => 1, 'b' => 2, 'c' => 3];
echo json_encode($arr, JSON_PRETTY_PRINT);
?>
Code execution result:
'{
"a": 1,
"b": 2,
"c": 3
}'
See Also
-
the
json_decode
function,
which converts a JSON string into PHP variables -
the
serialize
function,
which converts variables into a string for storage