JSON Processing in PHP: Complete Guide
JSON (JavaScript Object Notation) is a lightweight data interchange format that has become the standard for client-server communication. In PHP, JSON handling is implemented natively through the built-in functions json_encode() and json_decode(). In this article, we will thoroughly examine all aspects of JSON processing in PHP: from basic operations to advanced techniques and error handling.
Core Functions for Working with JSON in PHP
PHP provides two key tools for JSON processing:
- json_encode() — converts a PHP value (array, object, string) into a JSON string.
- json_decode() — decodes a JSON string back into a PHP value.
Basic Example of json_encode()
<?php// Source data: associative array$data = [ 'name' => 'Ivan', 'age' => 30, 'skills' => ['PHP', 'JavaScript', 'Python']];
// Encode to JSON$jsonString = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);echo $jsonString;?>Execution result:
{ "name": "Ivan", "age": 30, "skills": [ "PHP", "JavaScript", "Python" ]}The JSON_UNESCAPED_UNICODE flag preserves Cyrillic characters without escaping, and JSON_PRETTY_PRINT formats the output with indentation for readability.
Example of Decoding JSON in PHP
<?php$jsonString = '{"name":"Anna","age":25,"city":"Moscow"}';
// Decode into an associative array (second argument true)$array = json_decode($jsonString, true);echo $array['name']; // Annaecho $array['city']; // Moscow
// Decode into an object (default)$object = json_decode($jsonString);echo $object->name; // Anna?>Error Handling When Working with JSON
When working with external data, it is important to check the validity of JSON. Use json_last_error() and json_last_error_msg() for this:
<?php$invalidJson = '{name: "Error"}'; // Invalid JSON (key without quotes)
$decoded = json_decode($invalidJson);
if (json_last_error() !== JSON_ERROR_NONE) { $errorMsg = json_last_error_msg(); echo "JSON decoding error: $errorMsg"; // Output: JSON decoding error: Syntax error}?>Working with Nested Structures
JSON is excellent for complex hierarchical data. Consider an example with nested arrays and objects:
<?php$complexData = [ 'users' => [ [ 'id' => 1, 'name' => 'Peter', 'orders' => [ ['product' => 'Laptop', 'price' => 75000], ['product' => 'Mouse', 'price' => 1500] ] ], [ 'id' => 2, 'name' => 'Maria', 'orders' => [] ] ], 'total_orders' => 2];
$json = json_encode($complexData, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);file_put_contents('data.json', $json); // Save to file
// Read back$jsonFromFile = file_get_contents('data.json');$restoredData = json_decode($jsonFromFile, true);
// Access nested dataecho $restoredData['users'][0]['orders'][0]['product']; // Laptop?>Advanced Options for json_encode()
PHP supports many flags for fine-tuning encoding:
JSON_FORCE_OBJECT— forces encoding an array as an object.JSON_NUMERIC_CHECK— converts numeric strings to numbers.JSON_UNESCAPED_SLASHES— does not escape slashes.JSON_THROW_ON_ERROR— throws an exception on error (
Also in library
Event Bus and Observer Pattern in Kotlin: A Guide with Examples
Kotlin Application Configuration: Libraries, Approaches, and Tools
Swagger/OpenAPI Generation for Swift: Tools and Code Examples