Learn how to handle JSON in PHP with json_encode()
and json_decode()
. Convert arrays to JSON, parse JSON data, and manipulate it efficiently.
Introduction
JSON (JavaScript Object Notation) is a lightweight and widely-used format for storing and exchanging structured data. It is commonly used in APIs, configuration files, and data storage.
PHP provides built-in functions to encode, decode, and manipulate JSON data efficiently:
json_encode()
– Converts PHP arrays and objects into JSON format.json_decode()
– Converts JSON strings into PHP arrays or objects.
This guide covers:
- Encoding PHP arrays into JSON
- Decoding JSON strings into PHP objects and arrays
- Handling errors and special characters
- Best practices for working with JSON in PHP applications
1. Encoding PHP Data into JSON with json_encode()
The json_encode()
function converts PHP arrays and objects into a JSON string.
Basic JSON Encoding
$data = [
"name" => "John Doe",
"email" => "john@example.com",
"age" => 30
];
$json = json_encode($data);
echo $json;
// Output: {"name":"John Doe","email":"john@example.com","age":30}
- Converts an associative array into a JSON object.
- Ensures proper formatting for API responses and data exchange.
Encoding Multidimensional Arrays
$data = [
"users" => [
["id" => 1, "name" => "Alice"],
["id" => 2, "name" => "Bob"]
]
];
$json = json_encode($data);
echo $json;
// Output: {"users":[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]}
- Preserves nested structures within JSON.
2. Decoding JSON Strings into PHP with json_decode()
The json_decode()
function converts JSON data into PHP objects or arrays.
Decoding JSON as an Object
$json = '{"name":"John Doe","email":"john@example.com","age":30}';
$data = json_decode($json);
echo $data->name; // Output: John Doe
- Returns a PHP object by default.
Decoding JSON as an Associative Array
$data = json_decode($json, true);
echo $data["name"]; // Output: John Doe
- Passing
true
as the second argument returns a PHP associative array instead of an object.
Handling JSON Arrays
$json = '[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]';
$data = json_decode($json, true);
foreach ($data as $user) {
echo $user["name"] . "\n";
}
// Output:
// Alice
// Bob
3. Handling JSON Errors with json_last_error()
If json_encode()
or json_decode()
fails, it may return false
without providing details. Use json_last_error()
to check for errors.
Example: Detecting JSON Errors
$json = '{"name": "John Doe", "email": "john@example.com", "age": 30,'; // Missing closing brace
$data = json_decode($json);
if (json_last_error() !== JSON_ERROR_NONE) {
echo "JSON Error: " . json_last_error_msg();
}
// Output: JSON Error: Syntax error
json_last_error_msg()
provides a human-readable error message.
Common JSON Errors
Error Code | Description |
---|---|
JSON_ERROR_NONE |
No error |
JSON_ERROR_SYNTAX |
Syntax error in JSON string |
JSON_ERROR_UTF8 |
Malformed UTF-8 characters |
JSON_ERROR_DEPTH |
Maximum stack depth exceeded |
4. Working with Special JSON Options
json_encode()
and json_decode()
support additional options to handle formatting and encoding behavior.
Pretty Print JSON for Readability
$data = ["name" => "Alice", "email" => "alice@example.com"];
$json = json_encode($data, JSON_PRETTY_PRINT);
echo $json;
Output (Formatted JSON)
{
"name": "Alice",
"email": "alice@example.com"
}
- Makes JSON easier to read and debug.
Handling Unicode Characters
$data = ["text" => "Hello, 世界"];
$json = json_encode($data, JSON_UNESCAPED_UNICODE);
echo $json;
// Output: {"text":"Hello, 世界"}
- Prevents PHP from escaping non-ASCII characters.
Forcing JSON Object Output
If an empty array is encoded, PHP returns []
. To force JSON object notation, use JSON_FORCE_OBJECT
.
$data = [];
$json = json_encode($data, JSON_FORCE_OBJECT);
echo $json;
// Output: {}
- Ensures consistent JSON structure.
5. Modifying JSON Data in PHP
Merging JSON Objects
$json1 = '{"name":"Alice"}';
$json2 = '{"email":"alice@example.com"}';
$data1 = json_decode($json1, true);
$data2 = json_decode($json2, true);
$merged = json_encode(array_merge($data1, $data2));
echo $merged;
// Output: {"name":"Alice","email":"alice@example.com"}
- Converts JSON to PHP arrays, merges them, then re-encodes.
Updating JSON Values
$json = '{"name":"Alice","email":"alice@example.com"}';
$data = json_decode($json, true);
$data["email"] = "newemail@example.com";
$jsonUpdated = json_encode($data);
echo $jsonUpdated;
// Output: {"name":"Alice","email":"newemail@example.com"}
6. Best Practices for Handling JSON in PHP
✅ Always validate JSON input with json_last_error()
.
✅ Use JSON_PRETTY_PRINT
for debugging readable JSON.
✅ Use JSON_UNESCAPED_UNICODE
to keep special characters readable.
✅ Decode JSON as an array (true
flag) if working with associative arrays.
✅ Sanitize input before encoding JSON to prevent security risks.
✅ Check API responses before processing JSON to handle errors gracefully.
Conclusion
JSON is a fundamental part of PHP development, used in APIs, web applications, and data processing. Understanding how to encode, decode, and manipulate JSON ensures reliable and efficient data handling.
This guide covered:
- Encoding PHP arrays into JSON with
json_encode()
- Decoding JSON strings into PHP with
json_decode()
- Handling errors and special encoding options
- Modifying JSON data dynamically
By applying these techniques, you can efficiently manage JSON data in PHP applications, ensuring compatibility with APIs and structured data storage.