JSON (JavaScript Object Notation) is a lightweight data interchange format widely used in web development. It is based on JavaScript object notation, making it easy to handle and transmit data across different programming languages.
PHP offers the json_decode function to convert JSON strings into PHP arrays. Simply set the second parameter to true to get an array.
$json_string = '{"name": "John", "age": 30, "city": "New York"}'; $data = json_decode($json_string, true); print_r($data);
Output result:
Array ( [name] => John [age] => 30 [city] => New York )
If you want to convert a JSON string into a PHP object, you can omit the second parameter of json_decode, which returns an object by default.
$json_string = '{"name": "John", "age": 30, "city": "New York"}'; $data = json_decode($json_string); echo $data->name; // Outputs John
When JSON data is stored in a file, you can read it first with file_get_contents, then decode it with json_decode.
$json_string = file_get_contents('data.json'); $data = json_decode($json_string, true);
PHP provides the json_encode function to convert arrays or objects to JSON strings, which is useful for data transmission or storage.
$data = array( 'name' => 'John', 'age' => 30, 'city' => 'New York' ); $json_string = json_encode($data); echo $json_string; // Outputs: {"name":"John","age":30,"city":"New York"}
By default, json_encode escapes Unicode characters. Using the JSON_UNESCAPED_UNICODE option preserves Unicode characters, making it easier to display Chinese and other characters.
$data = array( 'name' => '张三', 'age' => 30, 'city' => '北京' ); $json_string = json_encode($data, JSON_UNESCAPED_UNICODE); echo $json_string; // Outputs: {"name":"张三","age":30,"city":"北京"}
In PHP, the json_decode and json_encode functions make it easy to convert between JSON and arrays or objects. They support reading data from files and handling Unicode characters, greatly simplifying JSON data manipulation in web applications.