PHP json_encode() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
JSON

Definition

In PHP, json_encode() converts a PHP value, such as an array or object, into a JSON string. It is the opposite of json_decode().

You use json_encode() when you want to send data to JavaScript, save it in a file, or return it from an API. Associative arrays and objects become JSON objects, and lists become JSON arrays. It returns false if encoding fails, or throws a JsonException with JSON_THROW_ON_ERROR.

Syntax

Call json_encode() with the values you need. Start with this line.

PHP
$json = json_encode($data, JSON_PRETTY_PRINT);
CallWhat it does
json_encode(['a' => 1, 'b' => 2])Returns the string {"a":1,"b":2}.
json_encode([1, 2, 3])Returns [1,2,3] because the array is a list.
json_encode($data, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR)Returns readable, indented JSON and throws a JsonException if encoding fails.

Combine several flags with the | operator. Use JSON_PRETTY_PRINT to make output easy to read, JSON_UNESCAPED_UNICODE and JSON_UNESCAPED_SLASHES to keep characters as they are, and JSON_THROW_ON_ERROR to handle failures with exceptions.

Library declarations
PHP
json_encode(mixed $value, int $flags = 0, int $depth = 512): string|false

Parameters

ParameterDescription
valueRequired. The value to encode. It can be any type except a resource. Strings must be valid UTF-8.
flagsOptional. A bitmask of options such as JSON_PRETTY_PRINT, JSON_UNESCAPED_UNICODE, JSON_UNESCAPED_SLASHES, JSON_THROW_ON_ERROR, JSON_FORCE_OBJECT and JSON_NUMERIC_CHECK. The default is 0.
depthOptional. The maximum nesting depth. The default is 512. It must be greater than 0, and encoding fails if the value is nested deeper than this.

Return Value

Return ValueDescription
stringThe JSON representation of the value.
falseReturned when encoding fails, for example with invalid UTF-8 text, NAN or INF, a resource, or a depth error. With JSON_THROW_ON_ERROR a JsonException is thrown instead.

PHP Examples

Example 1 — Arrays Become Objects or Lists

An associative array becomes a JSON object, while a plain list becomes a JSON array.

PHP
<?php
$user = [
    'name' => 'Asha',
    'age' => 25,
    'skills' => ['PHP', 'JS']
];

echo json_encode($user), PHP_EOL;
echo json_encode([1, 2, 3]), PHP_EOL;
echo json_encode([]), PHP_EOL;
echo json_encode(new stdClass()), PHP_EOL;

How It Works

  1. The associative array has string keys, so it becomes a JSON object with curly braces.
  2. The nested skills array is a list, so it becomes a JSON array with square brackets.
  3. A plain list like [1, 2, 3] becomes [1,2,3].
  4. An empty PHP array becomes [], while an empty stdClass object becomes {}.

Example 2 — Unicode, Slashes and Invalid UTF-8

By default json_encode() escapes non-ASCII characters and slashes. Special flags keep them readable, and invalid text makes the call fail.

PHP
<?php
$text = 'café/php';

echo json_encode($text), PHP_EOL;
echo json_encode($text, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;

$bad = hex2bin('b131');
var_dump(json_encode($bad));
echo json_last_error_msg(), PHP_EOL;

How It Works

  1. By default the letter é is written as a \u00e9 escape and the slash is written as \/.
  2. JSON_UNESCAPED_UNICODE and JSON_UNESCAPED_SLASHES keep the original characters.
  3. hex2bin('b131') creates a byte sequence that is not valid UTF-8.
  4. json_encode() returns false, and json_last_error_msg() explains the problem.

Example 3 — Pretty Print and Depth Limit

Use JSON_PRETTY_PRINT for readable output, and the depth argument with JSON_THROW_ON_ERROR to guard against deep nesting.

PHP
<?php
$data = ['a' => ['b' => ['c' => 1]]];

try {
    echo json_encode($data, JSON_THROW_ON_ERROR, 2);
} catch (JsonException $e) {
    echo "Error: ", $e->getMessage(), PHP_EOL;
}

echo json_encode($data, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR), PHP_EOL;

How It Works

  1. The data is nested three levels deep: a, then b, then c.
  2. A depth limit of 2 is too small, so PHP throws a JsonException because of JSON_THROW_ON_ERROR.
  3. The catch block prints the exception message.
  4. The second call uses the default depth and JSON_PRETTY_PRINT, which indents the JSON with four spaces.

Frequently Asked Questions

It converts a PHP value such as an array, object, string or number into a JSON string. It is often used to send data to JavaScript or to build API responses.
Pass JSON_PRETTY_PRINT as the second argument. PHP then adds line breaks and four-space indentation, which is great for debugging and for files people will read.
Common reasons are text that is not valid UTF-8, values like NAN or INF, resources that cannot be encoded, or data nested deeper than the depth limit. Use JSON_THROW_ON_ERROR to get a clear exception instead of false.
An empty PHP array has no keys, so PHP treats it as a list and writes []. If you need an empty JSON object, use new stdClass() or pass the JSON_FORCE_OBJECT flag.
Combine JSON_UNESCAPED_UNICODE and JSON_UNESCAPED_SLASHES with the | operator. Without them PHP writes characters like é as \u00e9 and slashes as \/.

Next: json_last_error()

json_last_error() returns the error code from the last json_decode() or json_encode() call.

json_last_error() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful