Home > Article > Backend Development > Convert an array or object to a JSON string using PHP's json_encode() function
JSON (JavaScript Object Notation) is a lightweight data exchange format that has become a common format for data exchange between web applications. PHP's json_encode() function can convert an array or object into a JSON string. This article will introduce how to use PHP's json_encode() function, including syntax, parameters, return values, and specific examples.
The syntax of the json_encode() function is as follows:
string json_encode(mixed $value, int $options = 0, int $depth = 512)
Among them, the $value parameter represents the value to be converted to a JSON string, which can be Is an array or object. The $options parameter represents the options when converting JSON strings. The optional values are as follows:
The $depth parameter indicates the limit of the recursion depth, which is used to prevent stack overflow. The default is 512.
When using the json_encode() function, you need to pay attention to the following points:
json_encode() function returns a string in JSON data format, and returns if an error occurs FALSE. If the JSON_PRETTY_PRINT option is used, the returned string will have indentation and newlines. You can use the echo or var_dump function to output it.
The following shows two specific examples of using the json_encode() function.
1) Convert the array to a JSON string
<?php $data = array('name'=>'Tom','age'=>18,'gender'=>'male'); $json = json_encode($data); echo $json; ?>
Output result:
{"name":"Tom","age":18,"gender":"male"}
2) Convert the object to a JSON string
<?php class Person { public $name; public $age; public $gender; } $person = new Person(); $person->name = "Tom"; $person->age = 18; $person->gender = "male"; $json = json_encode($person); echo $json; ?>
Output result :
{"name":"Tom","age":18,"gender":"male"}
To sum up, you can easily convert an array or object into a JSON string using PHP’s json_encode() function. Developers can select appropriate options to control the formatting and escaping of JSON strings as needed.
The above is the detailed content of Convert an array or object to a JSON string using PHP's json_encode() function. For more information, please follow other related articles on the PHP Chinese website!