PHP序列化(序列化)跟反序列化

來源:互聯網
上載者:User
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";}}


  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.