Syntax
The syntax for the json_encode() function is simple:
json_encode(value, flags, depth)
Parameters
The json_encode() function accepts three parameters:
- value (Required): This is the data you want to convert into JSON format. It can be an array, an object, or other serializable data.
- flags (Optional): This controls the behavior of the function. Commonly used flags include:
- JSON_PRETTY_PRINT: Formats the JSON output with whitespace for better readability.
- JSON_UNESCAPED_SLASHES: Prevents escaping of slashes.
- JSON_UNESCAPED_UNICODE: Prevents escaping of Unicode characters.
- depth (Optional): Specifies the maximum depth of the structure being encoded. The default is 512.
Return Value
The json_encode() function returns a JSON-encoded string on success or false on failure. If the input data cannot be converted (e.g., contains unsupported types), it will trigger an error.
Examples
Let’s discuss some practical examples to see how json_encode() works in real-world scenarios.
Example 1: Converting an Array to JSON
Here is a simple example of converting a PHP array to JSON:
<?php
$data = array(
"name" => "John Doe",
"age" => 25,
"skills" => array("PHP", "JavaScript", "Python")
);
$jsonData = json_encode($data);
echo $jsonData;
?>

You can also try this code with Online PHP Compiler
Run Code
Output:
{"name":"John Doe","age":25,"skills":["PHP","JavaScript","Python"]}
In this example, the associative array is converted into a JSON string with key-value pairs.
Example 2: Using Flags for Pretty Printing
To make the JSON output more readable, you can use the JSON_PRETTY_PRINT flag:
<?php
$data = array(
"name" => "John Doe",
"age" => 25,
"skills" => array("PHP", "JavaScript", "Python")
);
$jsonData = json_encode($data, JSON_PRETTY_PRINT);
echo $jsonData;
?>

You can also try this code with Online PHP Compiler
Run Code
Output:
{
"name": "John Doe",
"age": 25,
"skills": [
"PHP",
"JavaScript",
"Python"
]
}
This format is useful when you want to debug or display JSON data in a user-friendly way.
Example 3: Handling Unicode Characters
When working with multilingual data, the JSON_UNESCAPED_UNICODE flag ensures that Unicode characters are not escaped:
<?php
$data = array(
"name" => "José",
"language" => "Español"
);
$jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);
echo $jsonData;
?>

You can also try this code with Online PHP Compiler
Run Code
Output:
{"name":"José","language":"Español"}
Without this flag, the special characters would appear as escape sequences.
Example 4: Encoding Nested Structures
You can encode complex nested arrays or objects:
<?php
$data = array(
"name" => "John Doe",
"age" => 25,
"address" => array(
"city" => "New York",
"zipcode" => "10001"
)
);
$jsonData = json_encode($data, JSON_PRETTY_PRINT);
echo $jsonData;
?>

You can also try this code with Online PHP Compiler
Run Code
Output:
{
"name": "John Doe",
"age": 25,
"address": {
"city": "New York",
"zipcode": "10001"
}
}
This shows how well json_encode() handles nested data structures.
Example 5: Limiting Depth
To prevent encoding excessively deep structures, you can set the depth parameter:
<?php
$data = array(
"level1" => array(
"level2" => array(
"level3" => array(
"level4" => "Too Deep"
)
)
)
);
$jsonData = json_encode($data, 0, 3);
if ($jsonData === false) {
echo "Error: " . json_last_error_msg();
} else {
echo $jsonData;
}
?>

You can also try this code with Online PHP Compiler
Run Code
Output:
Error: Maximum stack depth exceeded
This prevents your application from crashing due to infinite recursion.
Adding Options to `json_encode()`
You can make the JSON string more readable by using the `JSON_PRETTY_PRINT` option. Here’s how:
<?php
$student = array(
"name" => "John Doe",
"age" => 21,
"courses" => array("Math", "Science", "History")
);
// Use JSON_PRETTY_PRINT for readable formatting
$jsonString = json_encode($student, JSON_PRETTY_PRINT);
echo $jsonString;
?>

You can also try this code with Online PHP Compiler
Run Code
Output
{
"name": "John Doe",
"age": 21,
"courses": [
"Math",
"Science",
"History"
]
}
This makes the JSON string easier to read, especially when dealing with large or nested data.
Frequently Asked Questions
What is json_encode() used for in PHP?
The json_encode() function is used to convert PHP data types such as arrays and objects into JSON format, which is widely used for APIs and data exchange between systems.
What does the JSON_PRETTY_PRINT flag do?
The JSON_PRETTY_PRINT flag formats the JSON output with indentation and whitespace to make it easier to read.
How can I debug errors in json_encode()?
Use the json_last_error_msg() function to retrieve a descriptive error message when json_encode() fails.
Conclusion
In this article, we discussed the json_encode() function in PHP, covering its syntax, parameters, and return values. We looked at its functionality through various examples, including converting arrays and objects, handling Unicode characters, and managing nested structures. Understanding json_encode() is essential for working with APIs and data exchange in modern web development.