Use of PHP serializer in Python

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)])

150 150 Burnignorance | Where Minds Meet And Sparks Fly!