PHP json_encode() Function

Quick summary: The PHP json_encode() function converts a value into a JSON string.

PHP json_encode() Syntax

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

PHP json_encode() Basic examples

var_dump(json_encode(['a'=>1,'b'=>2]));
PHP
Output:
string(13) "{"a":1,"b":2}"

Encodes an associative array as JSON.

PHP json_encode() Real-world usage

$data = ['status'=>'ok'];
echo json_encode($data);
PHP
Output:
{"status":"ok"}

Creates JSON API responses.

PHP json_encode() Edge cases

var_dump(json_encode(INF));
PHP
Output:
bool(false)

INF and NAN cannot be encoded by default.

PHP json_encode() Common mistakes

Ignoring encoding errors

json_encode can fail silently.

Incorrect
json_encode($data);
Correct
json_encode($data, JSON_THROW_ON_ERROR);

Enable exceptions for safer encoding.

PHP json_encode() Frequently Asked Questions

What does json_encode() do in PHP?

Converts a PHP value into a JSON string.

Why does json_encode() return false?

Encoding error, check json_last_error().

How to handle errors in json_encode()?

Use JSON_THROW_ON_ERROR flag.

Does json_encode() support UTF-8?

Yes, input must be UTF-8.

Use case?

APIs and data serialization.

Difference from serialize()?

JSON is language-independent.

Common mistake?

Passing invalid UTF-8.

Can encode objects?

Yes.

Performance?

Fast.

Can pretty print JSON?

Yes with JSON_PRETTY_PRINT.

Safe?

Yes.

Best practice?

Use flags for strict handling.

PHP json_encode() Related PHP Functions