PHP json_encode() Function
The json_encode() function converts a PHP value (array, object, etc.) to a JSON-formatted string.
Syntax
json_encode(mixed $value, int $flags = 0, int $depth = 512): string|false
Parameters
| Parameter | Type | Description |
|---|---|---|
$value |
mixed | The value to encode (array, object, string, number, etc.) |
$flags |
int | Bitmask of JSON constants (optional) |
$depth |
int | Maximum nesting depth (default: 512) |
Return Value
Returns a JSON encoded string on success, or false on failure.
Try It Online
Output
Click Run to execute your code
Common Flags
| Flag | Description |
|---|---|
JSON_PRETTY_PRINT |
Format output with whitespace for readability |
JSON_UNESCAPED_UNICODE |
Don't escape Unicode characters |
JSON_UNESCAPED_SLASHES |
Don't escape forward slashes |
JSON_FORCE_OBJECT |
Output object instead of array |
JSON_NUMERIC_CHECK |
Encode numeric strings as numbers |
More Examples
Pretty Print
<?php
$data = [
"name" => "John",
"age" => 30,
"city" => "NYC"
];
echo json_encode($data, JSON_PRETTY_PRINT);
/*
{
"name": "John",
"age": 30,
"city": "NYC"
}
*/
?>
Combining Flags
<?php
$data = [
"url" => "https://example.com/api",
"message" => "Hello World!"
];
$json = json_encode($data,
JSON_PRETTY_PRINT |
JSON_UNESCAPED_SLASHES |
JSON_UNESCAPED_UNICODE
);
echo $json;
?>
API Response
<?php
header('Content-Type: application/json');
$response = [
"success" => true,
"data" => [
"id" => 123,
"name" => "Product"
]
];
echo json_encode($response);
?>
Important: Always check for errors using
json_last_error() after encoding, especially with user-provided data.
Common Use Cases
- Building REST API responses
- Storing data in databases
- Passing data to JavaScript
- Configuration file generation
Related Functions
- json_decode() - Decode a JSON string
json_last_error()- Get last JSON errorjson_last_error_msg()- Get error message
Enjoying these tutorials?