Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

json_encode

Converts a value to a JSON string.

Syntax

json_encode(mixed $value, int $flags = 0): string|false

Parameters

ParameterTypeDescription
$valuemixedAn array, an object or a simple value.
$flagsintOptional. `JSON_UNESCAPED_UNICODE` keeps non-ASCII letters, `JSON_PRETTY_PRINT` adds indentation.

Return value

string|falseA JSON string, or `false` on failure.

Examples

An array to JSON:

<?php
 
echo json_encode(['name' => 'Anna', 'tags' => ['php', 'sql']]);

Output:

{"name":"Anna","tags":["php","sql"]}

Non-ASCII letters kept as is, and a readable layout:

<?php
 
echo json_encode(['city' => 'Zürich'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

Output:

{
    "city": "Zürich"
}

Notes

A list with keys numbered from zero becomes a JSON array, other arrays an object. To keep errors from going unnoticed, add the JSON_THROW_ON_ERROR flag.

See also

  • json_decode — Parses a JSON string.
  • var_dump — Prints the type and the value — for debugging.

Related recipes

In the tutorial

  • The JSON format — JSON in PHP — json_encode and json_decode, non-ASCII text, error handling and storing data in a file.

Thanks for reading!

Donate to the site — we work hard for you.