PHP JSON Handling with json_encode & json_decode

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" => "[email protected]",
    "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":"[email protected]","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": "[email protected]",
    "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": "[email protected]", "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] => [email protected]
    [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.

Similar Reads

PHP mail() Function: A Complete Guide

PHP mail() is a great built-in function for sending an email directly from your script for account confirmations, password resets, or sending notifications.…

PHP array_diff_uassoc: How to Compare Arrays with Keys

PHP array_diff_uassoc compares arrays by values and keys. You can also pass a custom function to compare keys in your…

PHP is_dir Function: Check if a Directory Exists

Sometimes, when you run a script, you may encounter an error because the directory you're trying to access doesn't exist.…

How to Connect PHP to MongoDB

Connecting PHP to MongoDB allows you to integrate database functionalities into your web applications. MongoDB is a NoSQL database that…

PHP Null: How to Assign and Check for Null Values

PHP introduced null to handle undefined or missing values. It helps prevent errors when you check if a variable exists.…

PHP Math: Essential Functions with Examples

PHP math may sound like a pretty simple thing, but I assure you it's a set of tools that will…

PHP array_key_exists: How it Works with Examples

The PHP array_key_exists function checks a given key in an array and tells if that key exists or not. Understand…

PHP array_all Function: How it Works with Examples

PHP 8.4 released a new built-in function, array_all checks to check if all array values meet a condition. It gives…

PHP MySQL ORDER BY: How to Sort Data in SQL?

Sorting data is one of those things we do all the time but rarely stop to think about. Whether you…

PHP OR Operator: Using || and or in Conditional Statements

The PHP OR operator has two renditions: either || or or. Both of these are useful logical operators when you want to introduce…

Previous Article

PHP Global Variables & Superglobals: A Complete Guide

Next Article

PHP XML Parsers: Everything You Need to Know

Write a Comment

Leave a Comment

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


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.