Upgrade your PHP application by switching from serialize() to JSON for faster, safer, and more efficient data handling across different platforms.
In PHP, the serialize() function has long been a popular choice for converting complex data structures into a storable string format. However, with the rise of web APIs, JavaScript, and modern data formats, JSON has become the preferred method for data storage and transfer. JSON, or JavaScript Object Notation, offers better interoperability, human readability, and native support in many languages, making it an ideal choice for modern PHP applications.
In this tutorial, we will explore why and how you should transition from serialize() to JSON in PHP. We’ll cover the differences between the two methods, how to convert existing code using serialize() to JSON, and how to handle edge cases in data serialization and deserialization. By the end of this guide, you will have a solid understanding of when and why to use JSON over serialize() and how to implement this transition smoothly.
Why Move from serialize() to JSON?
While the serialize() function is perfectly functional for serializing data, it has several drawbacks compared to JSON. Below are some reasons why JSON is becoming the standard for data serialization and transfer in PHP:
- Interoperability: JSON is widely supported across different programming languages and platforms, making it easier to share data between systems.
- Readability: JSON is human-readable, whereas serialized data is often hard to interpret by developers and system administrators.
- Size Efficiency: JSON tends to produce smaller strings compared to serialized data, which can help reduce storage and transfer size.
- Security: The use of
unserialize()in PHP can be a security risk when handling untrusted data. JSON parsing is generally considered safer. - Compatibility with JavaScript: Since JSON is natively supported by JavaScript, it makes transferring data between the server and frontend easier and more efficient.
Basic Syntax: serialize() vs JSON
Before we dive into advanced examples, let’s first compare the syntax of serializing data with serialize() and encoding it into JSON using json_encode().
Example: Using serialize() to Convert an Array to a String
<?php
$data = ['name' => 'John', 'age' => 30, 'email' => '[email protected]'];
$serialized_data = serialize( $data );
echo $serialized_data;Output:
a:3:{s:4:"name";s:4:"John";s:3:"age";i:30;s:5:"email";s:17:"[email protected]";}
While this serialized string is useful for storing or transferring data, it’s not easily readable. Let’s now refactor this using JSON.
Example: Using json_encode() to Convert an Array to a JSON String
<?php
$data = ['name' => 'John', 'age' => 30, 'email' => '[email protected]'];
$json_data = json_encode( $data );
echo $json_data;Output:
{"name":"John","age":30,"email":"[email protected]"}
The JSON output is much easier to read and compatible with JavaScript, making it more suitable for modern applications.
Understanding the Differences Between serialize() and JSON
The most significant difference between serialize() and JSON is that serialize() is specific to PHP, while JSON is a language-agnostic format. Here are some key differences:
- Data Structure Support: Both
serialize()and JSON support arrays and objects, butserialize()can handle more complex structures such as references, PHP-specific objects, and resources, which JSON cannot. - Cross-Language Usability: JSON is widely supported by almost all programming languages, while
serialize()is exclusive to PHP. - Security:
unserialize()can be vulnerable to object injection attacks, whereasjson_decode()is safer because it simply parses the data into an array or object.
Converting Serialized Data to JSON
If you’re working with an existing PHP codebase that uses serialize(), converting it to use JSON is straightforward. Here’s an example of how to refactor code that serializes data and stores it in a file, replacing serialize() with JSON.
Example: Refactoring Serialized Data to JSON
Original Code Using serialize()
<?php
$data = ['name' => 'Alice', 'role' => 'admin'];
$serialized_data = serialize( $data );
// Store serialized data in a file
file_put_contents( 'data.txt', $serialized_data );
// Retrieve and unserialize the data
$retrieved_data = unserialize( file_get_contents( 'data.txt' ) );
print_r( $retrieved_data );Refactored Code Using json_encode() and json_decode()
<?php
$data = ['name' => 'Alice', 'role' => 'admin'];
$json_data = json_encode( $data );
// Store JSON data in a file
file_put_contents( 'data.json', $json_data );
// Retrieve and decode the JSON data
$retrieved_data = json_decode( file_get_contents( 'data.json' ), true );
print_r( $retrieved_data );
In this refactored code, we use json_encode() to convert the array into a JSON string and store it in a file. To retrieve the data, we use json_decode(), passing true as the second parameter to convert the JSON back into an associative array.
Handling Object Serialization
When using serialize(), you can serialize entire PHP objects, which JSON cannot natively handle. If you need to serialize objects and want to switch to JSON, you must convert the object into an array or use PHP’s __sleep() and __wakeup() magic methods to customize the serialization process.
Example: Converting an Object to JSON
<?php
class User {
public $name;
public $email;
public function __construct( $name, $email ) {
$this->name = $name;
$this->email = $email;
}
// Convert the object to an array for JSON encoding
public function toArray() {
return get_object_vars( $this );
}
}
$user = new User( 'Bob', '[email protected]' );
$json_user = json_encode( $user->toArray() );
echo $json_user;
In this example, we define a toArray() method in the class to convert the object’s properties into an array, which can then be passed to json_encode(). This approach allows us to work with objects and JSON efficiently.
Performance Considerations
One important aspect to consider when choosing between serialize() and JSON is performance. In most cases, json_encode() and json_decode() are faster and more efficient than serialize() and unserialize(). This is especially true for large datasets, where JSON’s lighter structure results in faster serialization and deserialization times.
Benchmarking serialize() vs JSON
<?php
$data = array_fill( 0, 10000, ['name' => 'John', 'age' => 30] );
// Benchmark serialize()
$start = microtime( true );
$serialized_data = serialize( $data );
$end = microtime( true );
echo 'serialize(): ' . ( $end – $start ) . ' seconds';
// Benchmark json_encode()
$start = microtime( true );
$json_data = json_encode( $data );
$end = microtime( true );
echo 'json_encode(): ' . ( $end – $start ) . ' seconds';
In this benchmark, you can compare the time it takes to serialize and encode a large dataset. In many cases, you’ll find that json_encode() is faster due to its simpler structure and widespread optimization.
Best Practices for Using JSON in PHP
- Always check for errors: Use
json_last_error()after encoding or decoding JSON to ensure that no errors occurred. - Use associative arrays: When decoding JSON, use the second parameter of
json_decode()to convert the data into an associative array if you’re working with arrays in PHP. - Consider data size: JSON is typically more size-efficient, but for large objects or complex data structures, measure performance to ensure it’s optimal for your use case.
- Security: Avoid passing user-supplied data directly into
unserialize(). With JSON, you mitigate some of these risks by usingjson_decode().
Conclusion
Transitioning from serialize() to JSON for data storage and transfer in PHP is a wise move for modern applications. JSON offers better readability, performance, and security, while also being widely supported across different languages and platforms. By refactoring your code to use json_encode() and json_decode(), you can future-proof your applications and take advantage of the many benefits JSON has to offer.


