JSON Handling

Last updated on

JSON is used in most of your web applications for dealing with data, and so, in a way, PHP JSON handling has become part of the essentials which is a great way to represent your data in a lightweight, human-readable, and language-agnostic format. PHP developers commonly use JSON when processing the data transfer between the front end and back end, as the built-in functions such as json_encode and json_decode in PHP work smoothly to encode and decode data.

Through this tutorial, you will learn how PHP makes working with JSON rather effortless through the use of two major functions: json_encode() and json_decode().

These utilities will let you change data into JSON format so that handling data becomes easy and then change the JSON back into PHP-friendly formats. Each function does what it does, under the hood, to help with PHP JSON handling, as we shall see.

What is JSON? Why is it useful?

JSON (JavaScript Object Notation) is a format that is useful for storing and exchanging data in a structured way. It is widely used because it is both human-readable and lightweight; it allows complex data structures to be represented in a format that's easily accessible to people. JSON integrates well with JavaScript, making it a great option to transfer data from a client—for example, a browser—to a server and vice versa.

PHP supports the processing of JSON, allowing efficient, fast, and straightforward interaction with JSON data without using workarounds.

Next, we will look at how PHP data structures need to be converted into JSON format using json_encode() and how JSON data will be converted and made readable to PHP using json_decode().

Encoding Data to JSON using json_encode()

One of the major tasks when working with JSON data in PHP is converting PHP data structures, like arrays or objects, into JSON format. This is where json_encode() comes in. The json_encode() function takes a PHP variable and converts it into a JSON string. This now JSON-encoded content can then be sent to a client or used in various other parts of your application where JSON format is required. 

Using json_encode() is pretty simple. Let's look at a basic example. Suppose you have the following PHP array, which contains information about a user:

$user_data = [
    "name" => "John Doe",
    "email" => "john@example.com",
    "age" => 30
];
$json_data = json_encode($user_data);
echo $json_data;

The json_encode() function converts $user_data into a JSON string. The output of the above example might look like this:  

{"name":"John Doe","email":"john@example.com","age":30}

Let's take a look at the json_encode() options.

The json_encode() function in PHP also provides several optional flags that modify how data is encoded and can be helpful depending on what exactly you are trying to achieve, such as readability or handling complex data structures. Among the most useful flags are:

  • JSON_PRETTY_PRINT: The JSON string will be formatted with indentation so that it is more readable.
  • JSON_NUMERIC_CHECK: Numeric strings are encoded as numbers.
  • JSON_UNESCAPED_SLASHES: Prevents escaping of forward slashes (useful for URLs).
  • JSON_UNESCAPED_UNICODE: Does not escape Unicode characters.

Here is an example:

echo json_encode($user_data, JSON_PRETTY_PRINT);

This outputs the JSON in a more readable format:

{
    "name": "John Doe",
    "email": "john@example.com",
    "age": 30
}

Anyway, in the following section, you will learn how to decode JSON data with json_decode()

Parsing JSON Data with json_decode()

We have seen how to encode data, let's take a look at the reverse process—called decoding. PHP's json_decode() function takes a JSON string and converts it back into a PHP data structure. This is especially useful when receiving JSON data from a client, API, or other sources, which needs to be manipulated within your PHP code.  

Suppose we have the following JSON data stored in a string:

$json_string = '{"name": "John Doe", "email": "john@example.com", "age": 30}';
$data = json_decode($json_string, true);
print_r($data);

In this example, json_decode() returns an associative array from the JSON string because we passed the parameter true. The output would be:

Array
(
    [name] => John Doe
    [email] => john@example.com
    [age] => 30
)

If you prefer to work with objects rather than arrays, just omit the true parameter, and json_decode() will return a PHP object:  

Here is another example of decoding JSON to an object:

$data = json_decode($json_string);
echo $data->name; // Outputs: John Doe

Anyway, in the following section, you will learn how to handle errors in JSON decoding.

Handling Errors

When working with external JSON data, you should never assume that the data is valid. Fortunately, PHP json_decode() provides error-checking functions that help you handle invalid JSON gracefully. Use json_last_error() after decoding to check if an error occurred:  

$data = json_decode($json_string);
if (json_last_error() !== JSON_ERROR_NONE) {
    echo "Error decoding JSON: " . json_last_error_msg();
}

This will allow you to catch any specific issues, such as structural JSON mistakes, and handle errors before they impede your application’s functionality.

Wrapping Up

JSON handling in PHP is one of its most powerful features, enabling you to streamline data exchange and manage data structures with ease.

JSON opens up new possibilities for working with APIs, databases, and JavaScript. Understanding json_encode() and json_decode() will enhance your ability to handle data within PHP, making your applications more versatile and more readable.

To see more tutorials in PHP, click here.

Frequently Asked Questions (FAQs)

  • What is PHP JSON Handling?

    PHP JSON Handling refers to the process of encoding and decoding JSON data in PHP. With JSON being a popular format for data exchange, PHP provides built-in functions like json_encode and json_decode to make handling JSON straightforward. These functions convert PHP data structures to JSON format and vice versa, allowing seamless data communication between the front end and back end.
  • How does json_encode work in PHP?

    The json_encode function in PHP takes a PHP variable, such as an array or object, and converts it into a JSON string. This JSON-encoded data can be used wherever JSON format is needed, such as in API responses or data storage. Here’s an example:
    $user_data = [
        "name" => "John Doe",
        "email" => "john@flatcoding.com",
        "age" => 30
    ];
    $json_data = json_encode($user_data);
    echo $json_data;
    
  • What does json_decode do in PHP?

    The json_decode function in PHP takes a JSON string and converts it back into a PHP variable, such as an array or object, making it easier to work with in PHP code. Here’s how it works:
    $json_string = '{"name": "John Doe", "email": "john@example.com", "age": 30}';
    $data = json_decode($json_string, true);
    print_r($data);
    
  • Can json_encode handle special characters in php ?

    Yes, json_encode has options for handling special characters. For example, using the JSON_UNESCAPED_UNICODE option will prevent Unicode characters from being escaped. Here’s an example:
    $user_data = ["name" => "Jürgen Müller"];
    $json_data = json_encode($user_data, JSON_UNESCAPED_UNICODE);
    echo $json_data;
    
  • How can I check for errors in JSON decoding?

    PHP provides the json_last_error and json_last_error_msg functions to check for errors in JSON decoding. After using json_decode, you can check if any errors occurred. Here’s an example:
    $json_string = '{"name": "John Doe", "email": "john@example.com", "age": 30';
    $data = json_decode($json_string);
    if (json_last_error() !== JSON_ERROR_NONE) {
        echo "Error decoding JSON: " . json_last_error_msg();
    }
    
  • What is the difference between json_decode and json_encode?

    What is the difference between json_decode and json_encode? A: json_encode is used to convert PHP data into JSON format, while json_decode does the reverse, converting JSON data into PHP data structures. json_encode is helpful when sending data from PHP to JavaScript or APIs, and json_decode is useful when retrieving and manipulating JSON data within PHP.
  • How can I format JSON output to make it readable?

    You can make JSON output more readable by using the JSON_PRETTY_PRINT option with json_encode. This option formats the JSON with indentation and line breaks. Example:
    $user_data = [
        "name" => "John Doe",
        "email" => "john@example.com",
        "age" => 30
    ];
    echo json_encode($user_data, JSON_PRETTY_PRINT);
    
Share on: