本文主要介紹了php序列化函數serialize() 和 unserialize() 與php原生序列化方法比較。希望對大家有幫助。
php中有格式化字串並轉換成陣列或物件的好方法,即序列化處理。
有兩種序列化變數的方法。
以下範例,使用 serialize() 和 unserialize() 函數:
// a complex array
$myvar = array(
'hello',
42,
array(1,'two'),
'apple'
);
// convert to a string
$string = serialize($myvar);
echo $string;
/* prints
a:4:{i:0;s:5:"hello";i:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3:"two";}i:3;s:5:"apple";}
*/
// you can reproduce the original variable
$newvar = unserialize($string);
print_r($newvar);
/* prints
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => apple
)
*/這是原生的 PHP 序列化方法。
然而,由於 JSON 近年來大受歡迎,PHP5.2 中已經加入了對 JSON 格式的支援。
現在你可以使用json_encode() 和json_decode() 函數:
// a complex array
$myvar = array(
'hello',
42,
array(1,'two'),
'apple'
);
// convert to a string
$string = json_encode($myvar);
echo $string;
/* prints
["hello",42,[1,"two"],"apple"]
*/
// you can reproduce the original variable
$newvar = json_decode($string);
print_r($newvar);
/* prints
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => apple
)
*/這將更為行之有效,尤其與JavaScript 等許多其他語言相容。
注意:對於複雜的對象,某些資訊可能會遺失。
相關推薦:
####################################################################以上是php序列化函數serialize與原生方法對比的詳細內容。更多資訊請關注PHP中文網其他相關文章!