Table of contents
1.
Introduction
2.
Definition and Usage
2.1.
Why is `json_encode()` Important?
3.
Syntax
4.
Parameters
5.
Return Value
6.
Examples
6.1.
Example 1: Converting an Array to JSON
6.2.
Example 2: Using Flags for Pretty Printing
6.3.
Example 3: Handling Unicode Characters
6.4.
Example 4: Encoding Nested Structures
6.5.
Example 5: Limiting Depth
7.
Adding Options to `json_encode()`
8.
Frequently Asked Questions
8.1.
What is json_encode() used for in PHP? 
8.2.
What does the JSON_PRETTY_PRINT flag do?
8.3.
How can I debug errors in json_encode()? 
9.
Conclusion
Last Updated: Jan 25, 2025
Easy

PHP json encode() Function

Author Rahul Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

When working with PHP, managing data often requires converting it into a format that’s easily transferable between systems or platforms. This is where json_encode() comes in. It is a powerful PHP function that converts data types like arrays and objects into JSON format, which is widely used for APIs and web applications. 

PHP json_encode() Function

In this article, we will discuss how json_encode() works, its syntax, parameters, return values, and examples to help you understand it better.

Definition and Usage

The `json_encode()` function in PHP is used to convert a PHP value (like an array or an object) into a JSON string. JSON (JavaScript Object Notation) is a text-based format that is easy for humans to read & write & easy for machines to parse & generate. It’s commonly used for transmitting data in web applications, especially between a server & a client.

Why is `json_encode()` Important?

  • Data Exchange: JSON is a universal format for data exchange. When you’re working with APIs, you often need to send or receive data in JSON format.
     
  • Storage: JSON strings can be stored in databases or files, making it easy to save & retrieve structured data.
     
  • Compatibility: JSON is supported by almost all programming languages, making it a great choice for interoperability.

Syntax

The syntax for the json_encode() function is simple:

json_encode(value, flags, depth)

Parameters

The json_encode() function accepts three parameters:

  1. value (Required): This is the data you want to convert into JSON format. It can be an array, an object, or other serializable data.
     
  2. flags (Optional): This controls the behavior of the function. Commonly used flags include:
    • JSON_PRETTY_PRINT: Formats the JSON output with whitespace for better readability.
       
    • JSON_UNESCAPED_SLASHES: Prevents escaping of slashes.
       
    • JSON_UNESCAPED_UNICODE: Prevents escaping of Unicode characters.
       
  3. depth (Optional): Specifies the maximum depth of the structure being encoded. The default is 512.

Return Value

The json_encode() function returns a JSON-encoded string on success or false on failure. If the input data cannot be converted (e.g., contains unsupported types), it will trigger an error.

Examples

Let’s discuss some practical examples to see how json_encode() works in real-world scenarios.

Example 1: Converting an Array to JSON

Here is a simple example of converting a PHP array to JSON:

<?php
$data = array(
    "name" => "John Doe",
    "age" => 25,
    "skills" => array("PHP", "JavaScript", "Python")
);


$jsonData = json_encode($data);


echo $jsonData;
?>
You can also try this code with Online PHP Compiler
Run Code


Output:

{"name":"John Doe","age":25,"skills":["PHP","JavaScript","Python"]}


In this example, the associative array is converted into a JSON string with key-value pairs.

Example 2: Using Flags for Pretty Printing

To make the JSON output more readable, you can use the JSON_PRETTY_PRINT flag:

<?php
$data = array(
    "name" => "John Doe",
    "age" => 25,
    "skills" => array("PHP", "JavaScript", "Python")
);

$jsonData = json_encode($data, JSON_PRETTY_PRINT);

echo $jsonData;
?>
You can also try this code with Online PHP Compiler
Run Code


Output:

{
    "name": "John Doe",
    "age": 25,
    "skills": [
        "PHP",
        "JavaScript",
        "Python"
    ]
}


This format is useful when you want to debug or display JSON data in a user-friendly way.

Example 3: Handling Unicode Characters

When working with multilingual data, the JSON_UNESCAPED_UNICODE flag ensures that Unicode characters are not escaped:

<?php
$data = array(
    "name" => "José",
    "language" => "Español"
);

$jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);

echo $jsonData;
?>
You can also try this code with Online PHP Compiler
Run Code


Output:

{"name":"José","language":"Español"}


Without this flag, the special characters would appear as escape sequences.

Example 4: Encoding Nested Structures

You can encode complex nested arrays or objects:

<?php
$data = array(
    "name" => "John Doe",
    "age" => 25,
    "address" => array(
        "city" => "New York",
        "zipcode" => "10001"
    )
);

$jsonData = json_encode($data, JSON_PRETTY_PRINT);
echo $jsonData;
?>
You can also try this code with Online PHP Compiler
Run Code


Output:

{
    "name": "John Doe",
    "age": 25,
    "address": {
        "city": "New York",
        "zipcode": "10001"
    }
}


This shows how well json_encode() handles nested data structures.

Example 5: Limiting Depth

To prevent encoding excessively deep structures, you can set the depth parameter:

<?php
$data = array(
    "level1" => array(
        "level2" => array(
            "level3" => array(
                "level4" => "Too Deep"
            )
        )
    )
);

$jsonData = json_encode($data, 0, 3);

if ($jsonData === false) {
    echo "Error: " . json_last_error_msg();
} else {
    echo $jsonData;
}
?>
You can also try this code with Online PHP Compiler
Run Code


Output:

Error: Maximum stack depth exceeded


This prevents your application from crashing due to infinite recursion.

Adding Options to `json_encode()`

You can make the JSON string more readable by using the `JSON_PRETTY_PRINT` option. Here’s how:

<?php
$student = array(
    "name" => "John Doe",
    "age" => 21,
    "courses" => array("Math", "Science", "History")
);

// Use JSON_PRETTY_PRINT for readable formatting
$jsonString = json_encode($student, JSON_PRETTY_PRINT);

echo $jsonString;
?>
You can also try this code with Online PHP Compiler
Run Code


 Output

{
    "name": "John Doe",
    "age": 21,
    "courses": [
        "Math",
        "Science",
        "History"
    ]
}


This makes the JSON string easier to read, especially when dealing with large or nested data.

Frequently Asked Questions

What is json_encode() used for in PHP? 

The json_encode() function is used to convert PHP data types such as arrays and objects into JSON format, which is widely used for APIs and data exchange between systems.

What does the JSON_PRETTY_PRINT flag do?

 The JSON_PRETTY_PRINT flag formats the JSON output with indentation and whitespace to make it easier to read.

How can I debug errors in json_encode()? 

Use the json_last_error_msg() function to retrieve a descriptive error message when json_encode() fails.

Conclusion

In this article, we discussed the json_encode() function in PHP, covering its syntax, parameters, and return values. We looked at its functionality through various examples, including converting arrays and objects, handling Unicode characters, and managing nested structures. Understanding json_encode() is essential for working with APIs and data exchange in modern web development. 

Live masterclass