maciej-sz / pj-freeze
PHP to JSON Serializer/Deserializer
Installs: 1 232
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 2
Forks: 0
Open Issues: 0
Requires
- php: >=5.6
Requires (Dev)
- phpunit/phpunit: ^5.4
This package is not auto-updated.
Last update: 2024-12-19 04:13:20 UTC
README
PHP to JSON Serializer/Deserializer
Features
- Serialization to JSON
- Unserialization from JSON
- Circular-reference handling
- Corresponding JavaScript library is available to read serialized data on the browser side
Usage
This package can be used to serialize and unserialize data objects that contain circular references.
Example: basic round-trip
use MaciejSz\PjFreeze\PjFreeze; $Freeze = new PjFreeze(); $data = ["foo", "bar", "baz"]; $SerializationResult = $Freeze->serialize($data); $serializedObj = $SerializationResult->jsonSerialize(); $unserialized = $Freeze->unserialize($serializedObj); assert($data == $unserialized);
Example: persisting round-trip
An additional step is required for the serialization result to be persisted: PHP's standard json_encode()
function has to be called. The json_encode()
won't produce "Recursion detected" error this time.
use MaciejSz\PjFreeze\PjFreeze; $Freeze = new PjFreeze(); $data = ["foo", "bar", "baz"]; $serializedObj = $Freeze->serialize($data)->jsonSerialize(); $serialized_str = json_encode($serializedObj); file_put_contents("/tmp/data.json", $serialized_str); // ... $contents_str = file_get_contents("/tmp/data.json"); $unserialized = $Freeze->unserializeJson($contents_str); assert($data == $unserialized);
Example: circular reference
Using only json_encode()
:
// WARNING: this is an example of how NOT to encode circular references use MaciejSz\PjFreeze\PjFreeze; $data = new \stdClass(); $data->recursion = $data; // circular reference $raw_encoded = json_encode($data); echo json_last_error_msg(); // "Recursion detected"
Using PjFreeze
:
use MaciejSz\PjFreeze\PjFreeze; $data = new \stdClass(); $data->recursion = $data; // circular reference $Freeze = new PjFreeze(); $serializedObj = $Freeze->serialize($data)->jsonSerialize(); $jp_freeze_encoded = json_encode($serializedObj); echo json_last_error_msg(); // "No error" $unserializedObj = json_decode($jp_freeze_encoded); $unserialized = $Freeze->unserialize($unserializedObj); assert($unserialized->recursion === $unserialized);
Installation
Via composer:
composer require maciej-sz/pj-freeze