How to Use json_encode in PHP: Simple Guide and Examples
Use
json_encode in PHP to convert arrays or objects into a JSON string. Simply pass your data to json_encode, and it returns a JSON-formatted string that you can use for APIs or data storage.Syntax
The basic syntax of json_encode is simple. You pass the data you want to convert as the first argument. Optionally, you can add flags as the second argument to control the output format.
- value: The PHP array or object to convert.
- flags (optional): Bitmask options to modify encoding behavior.
- depth (optional): Maximum depth to traverse.
php
string json_encode(mixed $value, int $flags = 0, int $depth = 512)
Example
This example shows how to convert a PHP array into a JSON string using json_encode. The output is a JSON-formatted string representing the array.
php
<?php
$data = [
"name" => "Alice",
"age" => 25,
"city" => "New York"
];
$json = json_encode($data);
echo $json;
?>Output
{"name":"Alice","age":25,"city":"New York"}
Common Pitfalls
Common mistakes include trying to encode resources or non-UTF-8 strings, which cause json_encode to return false. Also, encoding objects with private or protected properties may not include those properties.
Always check the return value and use json_last_error() to detect errors.
php
<?php // Wrong: encoding a resource $file = fopen('file.txt', 'r'); $json = json_encode($file); var_dump($json); // bool(false) // Right: encode data only $data = ['file' => 'file.txt']; $json = json_encode($data); echo $json; ?>
Output
bool(false)
{"file":"file.txt"}
Quick Reference
| Option | Description |
|---|---|
| JSON_PRETTY_PRINT | Formats JSON with whitespace for readability |
| JSON_UNESCAPED_SLASHES | Prevents escaping of slashes |
| JSON_UNESCAPED_UNICODE | Outputs Unicode characters directly |
| JSON_FORCE_OBJECT | Outputs arrays as objects |
| JSON_NUMERIC_CHECK | Converts numeric strings to numbers |
Key Takeaways
Use json_encode to convert PHP arrays or objects into JSON strings easily.
Check json_encode's return value and use json_last_error() to catch encoding errors.
Avoid encoding resources or non-UTF-8 strings to prevent failures.
Use flags like JSON_PRETTY_PRINT to format JSON output for readability.
json_encode is essential for working with APIs and data exchange in PHP.