PHP serialize package is a port of the serialize and unserialize functions of PHP to Python.It will help us to serialize and universalize the complex data of dbs. Installation: First we need to install phpserializer package to python environment.
>>>pip install phpserialize Usage:
unserialize — Creates a PHP value from a stored representation unserialize() takes a single serialized variable and converts it back into a python value.
1)Example:Method of unserialization the data. >>>from phpserialize import serialize, unserialize >>>str = serialize({‘loginip’: ‘127.0.0.1’, ‘uid’: 96, ‘loginfrom’: 4,‘logintime’: 1317200595}) >>>print str …a:4:{s:7:”loginip”;s:9:”127.0.0.1″;s:3:”uid”;i:96;s:9:”loginfrom”;i:4;s:9: “logintime”;i:1317200595;} >>>print unserialize(str) …{‘loginip’: ‘127.0.0.1’, ‘uid’: 96, ‘loginfrom’: 4, ‘logintime’: 1317200595} |
2)Example:Method of serialization the data.
>>> from phpserialize import * >>> obj = dumps(“Hello World”) >>> loads(obj) ‘Hello World’ Due to the fact that PHP doesn’t know the concept of lists, lists are serialized like hash-maps in PHP. As a matter of fact the reverse value of a serialized list is a dict. >>> loads(dumps(range(2))) …{0: 0, 1: 1} If we want to have a list again, we can use the dict_to_list helper function: >>> dict_to_list(loads(dumps(range(2)))) …[0, 1]
It’s also possible to convert into a tuple by using the dict_to_tuple function:
>>> dict_to_tuple(loads(dumps((1, 2, 3)))) …(1, 2, 3)
Another problem are unicode strings. By default unicode strings are encoded to ‘utf-8’ but not decoded on unserialize. The reason for this is that phpserialize can’t guess if we have binary or text data in the strings:
>>> loads(dumps(u’Hello W\xf6rld’)) …’Hello W\xc3\xb6rld’
If you know that you have only text data of a known charset in the result you can decode strings by setting decode_strings to True when calling loads:
>>> loads(dumps(u’Hello W\xf6rld’), decode_strings=True) …u’Hello W\xf6rld’ >>> loads(dumps({None: 14, 42.23: ‘foo’, True: [1, 2, 3]})) …{”: 14, 1: {0: 1, 1: 2, 2: 3}, 42: ‘foo’} Array Serialization: >>> from collections import OrderedDict >>> loads(‘a:2:{s:3:”foo”;i:1;s:3:”bar”;i:2;}’, … array_hook=OrderedDict) collections.OrderedDict([(‘foo’, 1), (‘bar’, 2)]) |