PHP serialize vs json_encode

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

Data formats are interchangeable and this allows you to move back and forth between different data formats. This data transformation is usually necessary for data storage, transfer, and communication over a network in computers. The two most renowned data formats are JSON, XML, and CSV. JSON is quite common these days as RESTful APIs use JSON, thus many applications use JSON data to communicate with servers.

The image below shows a glimpse of a computer communicating with a server using JSON data.

php serialize vs json_encode

Many programming languages feature a built-in serialization interface that provides features for data transformation, usually specific to a programming language. Unlike JSON, XML, and CSV, serialized data is in the form of an encoded text, as we’ll see later. 

In this article about PHP serialize vs json_encode, we’ll explore serialization in PHP. We’ll see serialize function and compare it to json_encode. So, let’s move forward without any further delay.

PHP json_encode : Revisited

PHP has json_encode function returns JSON representation of a value. Quite often, PHP associative arrays are converted into JSON using this function. We have done an in-depth article about json_encode, how to convert array to JSON in PHP.

So, we won’t be iterating over fundamentals here rather we will see an example of an array converted to JSON by using the json_encode function.

<?php
//A user info array
$user_info = array("Id"=>1002,"Name"=>"Sam","isActive"=> true, "Friends"=>array("Natalia","Simon","Bob"));
 
//array_encode converts array into JSON string.
$user_json = json_encode($user_info,JSON_PRETTY_PRINT);
 
print_r($user_json);
 
/*
OUTPUT
{
    "Id": 1002,      
    "Name": "Sam",   
    "isActive": true,
    "Friends": [     
        "Natalia",   
        "Simon",     
        "Bob"        
    ]
}
*/
?>

So, you’ve just seen user_info array serialized into JSON format. From the output, we realize why JSON is a preferred data format.

Why JSON?

  • Readable –  JSON is human readable. You can read it and readily grasp the idea of what its describing.
  • Editable    – JSON can be edited inplace. You can always edit the human readable properties, thus JSON is much flexible to changes and editing.
  • Platform Independent – JSON can be used across different applications and platforms. Almost every programming language has functions for parsing JSON.

Given these properties, JSON is the right data format for APIs. Similarly, XML, which is a markup language is also a good choice for APIs. However, in the next section, we’ll see why the PHP serialize function might not be a good choice for API development.

PHP serialize vs json_encode : serialize function

PHP serialize is a built-in function in PHP that transforms data types into a byte stream representation. The serialize function outputs an encoded stream that helps PHP to persist the value and type of the original input. So, when you do the reverse of serialization, that is deserialization you get the original input.

Let’s see the anatomy of this function before an example.

Description

PHP serialize outputs a storable representation of a value.

serialize(mixed $value): string

 Arguments

  • $value – The value to be serialized

Return Type

A string containing a byte representation of the value.

<?php
//A user info array
$user_info = array("Id"=>1002,"Name"=>"Sam","isActive"=> true, "Friends"=>array("Natalia","Simon","Bob"));
 
//serialize converts array into byte stream.
$user_bytes = serialize($user_info);
 
print_r($user_bytes);
 
/*
OUTPUT
a:4:{s:2:"Id";i:1002;s:4:"Name";s:3:"Sam";s:8:"isActive";b:1;s:7:"Friends";a:3:{i:0;s:7:"Natalia";i:1;s:5:"Simon";i:2;s:3:"Bob";}}
*/
?>

You cannot comprehend the output because unlike JSON or XML it isn’t human readable. As mentioned already, it is byte stream representations. Byte streams are machine readable and only your machine can interpret it.

The output reveals some shortcomings of this type of representation. The reasons why we cannot use this data format in APIs.

  • Not Readable – The byte streams are not human readable. 
  • Non-Editable  –  The byte streams cannot be changed or modified manually. You will always need to rerun the code for accommodating changes.
  • Platform-dependent – Byte representation varies from machine to machine. Moreover, every programming language uses a different decoding algorithm. So, this representation may not integrate with other platforms. 

Given these properties, byte representation is just not feasible for APIs. So, the question is why use them in the first place? Well, there are some instances where you might need a data format that takes less storage space than other formats like JSON and XML.

These byte streams can be saved to a disk, file, or database and later retrieved for deserialization. This workflow is shown in the diagram.

PHP serialize vs json_encode : A comparison

We’ve seen both these functions and how do they differ. Here’s a quick overview of the differences between the PHP serialize and json_encode.

serializejson_encode
Returns byte representation of a valueReturns JSON representation of a value
The reverse function is unserializeThe reverse function is json_decode
Built-in serialize function is platform dependentjson_encode returns JSON and JSON is platform independent.
Byte streams are not human readableJSON is human readable.
serialize vs json_encode

Conclusion

In PHP serialize vs json_encode, we have seen and compared the two functions. Generally, json_encode is widely used due to its upsides. However, it is important to get an idea of different data formats and how built-in serialize works in PHP. We hope you’ve learned something new today. Stay tuned for more interesting PHP articles.

Want to explore more useful PHP tutorials?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

How to take form inputs and put them into a PHP associative array

How to put values in an associative array into another array in PHP

Tell if an element is present in an associative array PHP

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.