JSON (JavaScript Object Notation) is a lightweight data interchange format that has become a widely adopted standard in web development. PHP offers built-in functions to parse and generate JSON data, making it easy for developers to exchange data with front-end applications or other systems. This article systematically introduces how to use PHP’s JSON functions with practical code demonstrations.
The json_decode function converts a JSON formatted string into a PHP variable. The basic syntax is:
mixed json_decode(string $json[, bool $assoc = FALSE[, int $depth = 512[, int $options = 0]]])
Parameters:
$json_str = '{"name":"John", "age":30, "city":"New York"}'; $obj = json_decode($json_str); <p>echo $obj->name; // Output: John<br> echo $obj->age; // Output: 30<br> echo $obj->city; // Output: New York<br>
$json_str = '{"name":"John", "age":30, "city":"New York"}'; $assoc_arr = json_decode($json_str, true); <p>echo $assoc_arr["name"]; // Output: John<br> echo $assoc_arr["age"]; // Output: 30<br> echo $assoc_arr["city"]; // Output: New York<br>
This function returns the error code of the last json_decode operation, which helps in error handling. The syntax is:
int json_last_error()
$json_str = '{"name":"John, "age":30, "city":"New York"}'; $obj = json_decode($json_str); <p>if (json_last_error() !== JSON_ERROR_NONE) {<br> echo "JSON parsing error: " . json_last_error_msg();<br> }<br>
The json_encode function converts PHP data into a JSON formatted string. The basic syntax is:
string json_encode(mixed $value[, int $options = 0[, int $depth = 512]])
Parameters:
$arr = array("name" => "John", "age" => 30, "city" => "New York"); $json_str = json_encode($arr); <p>echo $json_str; // Output: {"name":"John","age":30,"city":"New York"}<br>
$arr = array("name" => "John", "age" => 30, "city" => "New York"); $json_str = json_encode($arr, JSON_PRETTY_PRINT); <p>echo $json_str;<br> // Output:<br> // {<br> // "name": "John",<br> // "age": 30,<br> // "city": "New York"<br> // }<br>
This function is also useful to check for errors during json_encode operations, returning the last JSON encoding error code. Usage is the same as with decoding.
$arr = array("name" => "John", "age" => 30, "city" => "New York"); $json_str = json_encode($arr); <p>if (json_last_error() !== JSON_ERROR_NONE) {<br> echo "JSON encoding error: " . json_last_error_msg();<br> }<br>
This article explained the fundamental usage of PHP’s json_decode and json_encode functions, supported by multiple code examples. Mastering these functions helps developers effectively handle data exchange between PHP and other systems.
When working with JSON data, always check for errors in parsing or encoding to avoid unexpected issues. The json_last_error and json_last_error_msg functions provide convenient error detection and debugging support.