PHP序列化(序列化)和反序列化
這個和java的序列話是一樣的。只是java要實現Serializable這個空介面。
serialize() 把變數和它們的值編碼成文本形式
unserialize() 恢複原先變數
什麼情況下需要序列化 當你想把的記憶體中的對象寫入到硬碟 資料庫的時候;當你想在網路上傳送對象的時候;
當把這些序列化的資料放在URL中在頁面之間會傳遞時,需要對這些資料調用urlencode(),以確保在其中的URL元字元進行處理
margic_quotes_gpc和magic_quotes_runtime配置項的設定會影響傳遞到unserialize()中的資料。
如果magic_quotes_gpc項是啟用的,那麼在URL、POST變數以及cookies中傳遞的資料在還原序列化之前必須用stripslashes()進行處理:
如果magic_quotes_runtime是啟用的,那麼在向檔案中寫入序列化的資料之前必須用addslashes()進行處理,而在讀取它們之前則必須用stripslashes()進行處理:
也可用array,把一個數組對象系列化。
index = $index;$this->name = $name;}}$data1 = new Data(1, "hello");$data2 = new Data(2, "world");$arr = array();//用ArrayObject也可以。//$arr = new ArrayObject();$arr[0] = $data1;$arr[1] = $data2;$str = serialize($arr);$file = fopen("tmp.txt", "w");fwrite($file, $str);fclose($file);//$file =fopen("tmp.txt", "r");$data = file_get_contents("tmp.txt");//還原序列化得到原來的數組對象。$obj = unserialize($data);print_r($obj[0]);echo $obj[0]->name;?>
tmp.txt的內容為:
a:2:{i:0;O:4:"Data":2:{s:5:"index";i:1;s:4:"name";s:5:"hello";}i:1;O:4:"Data":2:{s:5:"index";i:2;s:4:"name";s:5:"world";}}