JSON processing in PHP: complete guide
JSON (JavaScript Object Notation) is a lightweight data interchange format that has become the de facto standard for server-client communication. In PHP, working with JSON is implemented natively through the json extension, which has been available since PHP 5.2.0. In this article, we will thoroughly cover the main functions, error handling, working with nested structures, and best practices.
Main functions for working with JSON
PHP provides two key functions:
json_encode()— converts a PHP value (array, object, string, etc.) into a JSON string.json_decode()— converts a JSON string back into a PHP variable (array or object).
Example: encoding an array to JSON
<?php$data = [ 'name' => 'Alice', 'age' => 30, 'is_student' => false, 'skills' => ['PHP', 'JavaScript', 'Python']];
$json = json_encode($data, JSON_PRETTY_PRINT);echo $json;?>Result:
{ "name": "Alice", "age": 30, "is_student": false, "skills": [ "PHP", "JavaScript", "Python" ]}Example: decoding JSON to an array
<?php$jsonString = '{"name":"Bob","age":25,"is_active":true}';
// Second parameter true — returns an associative array$array = json_decode($jsonString, true);print_r($array);?>Result:
Array( [name] => Bob [age] => 25 [is_active] => 1)Flags for fine-tuning
The json_encode() and json_decode() functions support a second parameter — a bitmask of flags. Let's look at the most useful ones:
- JSON_PRETTY_PRINT — formats the output with indentation (for readability).
- JSON_UNESCAPED_UNICODE — does not escape Unicode characters (useful for Cyrillic).
- JSON_FORCE_OBJECT — forcibly converts an associative array into an object.
- JSON_NUMERIC_CHECK — converts strings containing numbers into numeric type.
Example with Cyrillic and formatting
<?php$data = [ 'name' => 'Алексей', 'city' => 'Москва'];
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);?>Result:
{ "name": "Алексей", "city": "Москва"}Error handling when working with JSON
If the input string is not valid JSON, json_decode() will return null. To find out the exact cause of the error, use the json_last_error() and json_last_error_msg() functions.
<?php$invalidJson = '{name: "Alice"}'; // Invalid JSON (keys without quotes)
$result = json_decode($invalidJson);if (json_last_error() !== JSON_ERROR_NONE) { echo 'Error: ' . json_last_error_msg();} else { print_r($result);}?>Output:
Error: Syntax errorFull list of error constants:
JSON_ERROR_NONE— no errors.JSON_ERROR_DEPTH— the maximum stack depth has been exceeded.JSON_ERROR_STATE_MISMATCH— invalid JSON (mismatched brackets).JSON_ERROR_SYNTAX— syntax error.JSON_ERROR_UTF8— malformed UTF-8 encoding.
Working with nested structures
JSON often contains nested objects and arrays. PHP allows you to easily process such data using recursion or loops.
<?php$complexJson = '{ "users": [ {"name": "Alice"