📅  最后修改于: 2023-12-03 14:43:34.975000             🧑  作者: Mango
json_encode()
is a PHP function that converts a PHP value to a JSON string. JSON, or JavaScript Object Notation, is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate.
string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
$value
: The value being encoded. Can be any type except a resource.$options
(optional): Bitmask consisting of JSON_FORCE_OBJECT
, JSON_NUMERIC_CHECK
, JSON_PRETTY_PRINT
, JSON_UNESCAPED_UNICODE
, JSON_UNESCAPED_SLASHES
, and JSON_PARTIAL_OUTPUT_ON_ERROR
. Default is 0
.$depth
(optional): Maximum depth. Must be greater than 0. Default is 512
.$data = array(
"name" => "John Doe",
"age" => 30,
"city" => "New York"
);
$json = json_encode($data);
echo $json;
The output will be:
{"name":"John Doe","age":30,"city":"New York"}
JSON_FORCE_OBJECT
: Encodes associative arrays as objects instead of arrays.JSON_NUMERIC_CHECK
: Encodes numeric strings as numbers.JSON_PRETTY_PRINT
: Formats the output with whitespace and indentation.JSON_UNESCAPED_UNICODE
: Does not escape Unicode characters.JSON_UNESCAPED_SLASHES
: Does not escape /
characters.JSON_PARTIAL_OUTPUT_ON_ERROR
: Returns partial output if an error occurs during encoding.With json_encode()
, programmers can easily convert a PHP value to a JSON string. This function is essential for sending and receiving data between PHP and client-side JavaScript applications. However, be aware of the available options when encoding values to ensure the desired output.