PHP Serialize for Python
phpserialize is a Python library that ports the `serialize` and `unserialize` functions of PHP, allowing Python applications to encode and decode data in PHP's native serialization format. It implements the standard Python serialization interface, providing `dumps` and `loads` functions. The current version is 1.3, with the last update in 2012, making it in a maintenance phase rather than actively developed, though it officially supports Python 3.
Warnings
- gotcha In Python 3, `loads` (unserialize) expects byte strings as input. All string-like values (keys, string contents) in the deserialized output will also be byte strings by default. You must explicitly decode them or use the `decode_strings=True` parameter during `loads`.
- gotcha PHP's serialization format has specific ways of handling objects and arrays. When deserializing PHP objects into Python, a custom `object_hook` is often required to map PHP class names to Python classes or dictionaries. Similarly, Python lists and tuples are not distinct PHP types and are typically serialized as PHP associative arrays.
- deprecated The original `phpserialize` library has not seen active development since version 1.3 in 2012. While it states Python 3 support, newer Python versions might encounter subtle compatibility issues not addressed by new releases. A community fork, `phpserialize3`, exists specifically for Python 3, which might offer more up-to-date compatibility, although it also appears to be infrequently updated.
Install
-
pip install phpserialize
Imports
- dumps
from phpserialize import dumps
- loads
from phpserialize import loads
- phpobject
from phpserialize import phpobject
Quickstart
from phpserialize import dumps, loads
# Basic serialization of a string
python_string = 'Hello World'
php_serialized_string = dumps(python_string)
print(f"Serialized string: {php_serialized_string}")
assert loads(php_serialized_string) == b'Hello World'
# Deserialization of a simple PHP array string (as bytes for Python 3)
php_array_data = b'a:1:{s:3:"key";s:5:"value";}'
python_dict = loads(php_array_data)
print(f"Deserialized array: {python_dict}")
# Note: Keys and string values are bytes in Python 3, require decoding
assert python_dict[b'key'] == b'value'
# Deserialization with string decoding
python_dict_decoded = loads(php_array_data, decode_strings=True)
print(f"Deserialized array (decoded): {python_dict_decoded}")
assert python_dict_decoded['key'] == 'value'
# Object serialization example (requires special handling)
# Using a simple PHP object string from a stdClass
php_object_data = b'O:8:"stdClass":1:{s:3:"baz";s:3:"qux";}'
from phpserialize import phpobject
python_obj = loads(php_object_data, object_hook=phpobject, decode_strings=True)
print(f"Deserialized object: {python_obj}")
assert python_obj['baz'] == 'qux'