What Is json_encode? PHP Examples, Syntax, and Common Mistakes

What Is json_encode? PHP Examples, Syntax, and Common Mistakes

By:

Date:

json_encode() is one of the most commonly used PHP functions for turning data into JSON, a lightweight format used by APIs, JavaScript applications, configuration files, and server responses. It helps PHP applications share arrays, objects, strings, numbers, and booleans in a format that other systems can easily read.

TLDR: json_encode() converts PHP values into JSON strings. It is often used when building APIs, sending data to JavaScript, or storing structured information. Developers should watch for encoding errors, invalid characters, unexpected array formats, and missing options such as JSON_PRETTY_PRINT or JSON_UNESCAPED_UNICODE.

What Is json_encode() in PHP?

json_encode() is a built-in PHP function that converts a PHP value into a JSON-formatted string. JSON, short for JavaScript Object Notation, is widely used because it is readable, compact, and supported by almost every modern programming language.

For example, a PHP associative array can be converted into a JSON object, while a regular indexed array can be converted into a JSON array. This makes json_encode() especially useful when a PHP backend needs to communicate with a frontend framework, mobile application, or external service.

Basic Syntax

The standard syntax of json_encode() is:

json_encode(mixed $value, int $flags = 0, int $depth = 512): string|false
  • $value: The PHP value to encode, such as an array, object, string, integer, float, boolean, or null.
  • $flags: Optional constants that control how JSON is generated.
  • $depth: The maximum depth of nested structures. The default is 512.

If encoding succeeds, the function returns a JSON string. If it fails, it returns false, although modern PHP code often uses JSON_THROW_ON_ERROR to throw an exception instead.

Simple PHP Examples

A basic example begins with an indexed array:

<?php
$colors = ["red", "green", "blue"];

echo json_encode($colors);
?>

The output is:

["red","green","blue"]

An associative array becomes a JSON object:

<?php
$user = [
    "id" => 101,
    "name" => "Maria",
    "active" => true
];

echo json_encode($user);
?>

The output is:

{"id":101,"name":"Maria","active":true}

This behavior is important because JSON distinguishes between arrays and objects. PHP decides the JSON structure based on the array keys.

Using json_encode() with Objects

PHP objects can also be encoded. Public properties are included in the JSON output:

<?php
class Product {
    public $name = "Laptop";
    public $price = 899.99;
}

$product = new Product();

echo json_encode($product);
?>

The output is:

{"name":"Laptop","price":899.99}

Private and protected properties are not encoded directly. When more control is needed, a class can implement JsonSerializable and define exactly what should appear in the JSON result.

Useful Encoding Options

json_encode() supports flags that change the output. These options can improve readability, preserve characters, or make error handling safer.

  • JSON_PRETTY_PRINT: Formats JSON with spaces and line breaks.
  • JSON_UNESCAPED_UNICODE: Keeps Unicode characters readable instead of escaping them.
  • JSON_UNESCAPED_SLASHES: Prevents slashes from being escaped.
  • JSON_THROW_ON_ERROR: Throws an exception if encoding fails.
  • JSON_NUMERIC_CHECK: Converts numeric strings into numbers, although it should be used carefully.

Example with pretty printing:

<?php
$data = [
    "site" => "Example",
    "status" => "online",
    "users" => 245
];

echo json_encode($data, JSON_PRETTY_PRINT);
?>

The output is easier to read:

{
    "site": "Example",
    "status": "online",
    "users": 245
}

Handling Errors Properly

A common mistake is assuming that json_encode() always works. Encoding can fail for several reasons, including invalid UTF-8 characters, excessive nesting, or unsupported values.

Older code often checks errors like this:

<?php
$result = json_encode($data);

if ($result === false) {
    echo json_last_error_msg();
}
?>

Modern PHP code can be cleaner with JSON_THROW_ON_ERROR:

<?php
try {
    $json = json_encode($data, JSON_THROW_ON_ERROR);
    echo $json;
} catch (JsonException $e) {
    echo "JSON error: " . $e->getMessage();
}
?>

This approach makes failures more visible and easier to handle in production applications.

Common Mistakes with json_encode()

1. Confusing Indexed Arrays and Associative Arrays

If a PHP array has sequential numeric keys starting at zero, it becomes a JSON array. If the keys are strings or non-sequential numbers, it becomes a JSON object.

<?php
$items = [
    1 => "first",
    2 => "second"
];

echo json_encode($items);
?>

This outputs an object, not an array:

{"1":"first","2":"second"}

To force a normal JSON array, the array can be reindexed with array_values().

2. Forgetting the Correct Content Type

When PHP returns JSON from an API endpoint, the response should include a JSON content type:

<?php
header("Content-Type: application/json");

echo json_encode(["success" => true]);
?>

Without this header, clients may treat the response as plain text or HTML.

3. Ignoring Unicode Output

By default, PHP may escape Unicode characters:

<?php
echo json_encode(["city" => "München"]);
?>

The result may be less readable. Using JSON_UNESCAPED_UNICODE keeps the text clearer:

<?php
echo json_encode(["city" => "München"], JSON_UNESCAPED_UNICODE);
?>

4. Encoding Database Results Without Cleaning Them

Database data may contain invalid encodings, unexpected null values, or sensitive fields. Before encoding, an application should remove private information, normalize values, and ensure strings are valid UTF-8.

5. Using JSON_NUMERIC_CHECK Carelessly

JSON_NUMERIC_CHECK converts numeric-looking strings into numbers. This can break phone numbers, postal codes, and IDs that must remain strings.

<?php
$data = ["phone" => "+33123456789"];

echo json_encode($data, JSON_NUMERIC_CHECK);
?>

The output can change the meaning of the data. For identifiers and phone numbers, it is usually safer to keep strings as strings.

Best Practices

  • Use JSON_THROW_ON_ERROR for reliable error handling.
  • Set Content-Type: application/json when returning JSON responses.
  • Use JSON_PRETTY_PRINT for debugging, not necessarily for large production responses.
  • Use JSON_UNESCAPED_UNICODE when readable international text matters.
  • Validate and sanitize data before encoding it.
  • Be careful with array keys, since they affect whether JSON becomes an array or object.

FAQ

What does json_encode() do in PHP?

It converts a PHP value, such as an array or object, into a JSON-formatted string.

Does json_encode() return an array?

No. It returns a string containing JSON, or false if encoding fails without exception handling.

How can JSON output be made readable?

The JSON_PRETTY_PRINT flag adds indentation and line breaks to the generated JSON.

Why does a PHP array become a JSON object?

If the PHP array has string keys or non-sequential numeric keys, json_encode() represents it as a JSON object.

What is the safest way to handle encoding errors?

The safest common approach is using JSON_THROW_ON_ERROR inside a try and catch block.

Categories:

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *