1. Serialize and Unserialize functions
These two are common functions for serializing and deserializing data in PHP.
<?PHP$a=Array(' a ' = ' Apple ', ' b ' = ' banana ', ' c ' = ' Coconut ');//Serializing Arrays$s=Serialize($a);Echo $s;//output: a:3:{s:1: "a"; S:5: "Apple"; s:1: "B"; S:6: "Banana"; s:1: "C"; s:7: "Coconut";}Echo' <br/><br/> ';//deserialization$o=unserialize($s);Print_r($o);//output Array ([a] + Apple [b] = banana [c] = = Coconut)?>
Problems can occur when an array value contains characters such as double quotes, single quotes, or colons, which are deserialized. To overcome this problem, a clever trick is to use Base64_encode and Base64_decode.
$obj = Array ();//Serialization $s = Base64_encode (serialize ($obj)); Deserialization $original = Unserialize (Base64_decode ($s));
But base64 encoding will increase the length of the string. To overcome this problem, you can use it with gzcompress.
Defines a function to serialize an object
function My_serialize ($obj) {return Base64_encode (gzcompress (Serialize ($obj)));} Deserialization function My_unserialize ($txt) {return unserialize (gzuncompress (Base64_decode ($txt)));}
2. Json_encode and Json_decode
Serializing and deserializing using JSON format is a good choice:
- Using Json_encode and Json_decode format output is much faster for serialize and unserialize formats.
- The JSON format is readable.
- The JSON format is smaller than the serialize return data result.
- The JSON format is open and portable. It can also be used in other languages.
$a = Array (' a ' = = ' Apple ', ' b ' = ' banana ', ' c ' = ' Coconut ');//serialized Array $s = json_encode ($a); echo $s;//output: {"A": "A" Pple "," B ":" Banana "," C ":" Coconut "}echo ' <br/><br/> ';//deserialization $o = Json_decode ($s);
In the above example, the Json_encode output length is obviously shorter than the serialize output length in the previous example.
3. Var_export and Eval
The Var_export function outputs the variable as a string, and Eval executes the string as PHP code, deserializing the contents of the original variable. $a = Array (' a ' = = ' Apple ', ' b ' = ' banana ', ' c ' = ' Coconut ');//serialize Array $s = Var_export ($a, true); echo $s;//output result: Array (' a ' = ' = ' Apple ', ' b ' = ' banana ', ' c ' = ' Coconut ', ' echo ' <br/><br/> ';//Deserialize eval (' $my _var= ') . $s. ‘;‘); Print_r ($my _var);
4. Wddx_serialize_value and WDDX Deserialize
The Wddx_serialize_value function can serialize array variables and output them as XML strings.
View Source print?
$a = Array (' a ' + = ' Apple ', ' b ' = ' banana ', ' c ' = ' Coconut ');//serialized Array $s = wddx_serialize_value ($a); echo $s;//Output junction Fruit (view source of output String): <wddxpacket version= ' 1.0 ' >
Reproduced at random, but please bring the address of this article:
http://www.nowamagic.net/librarys/veda/detail/2153
PHP multiple serialization/deserialization method (reprint)