zoukankan      html  css  js  c++  java
  • How to use php serialize() and unserialize()

    A PHP array or object or other complex data structure cannot be transported or stored or otherwise used outside of a running PHP script. If you want to persist such a complex data structure beyond a single run of a script, you need to serialize it. That just means to put the structure into a "lower common denominator" that can be handled by things other than PHP, like databases, text files, sockets. The standard PHP function serialize is just a format to express such a thing, it serializes a data structure into a string representation that's unique to PHP and can be reversed into a PHP object using unserialize. There are many other formats though, like JSON or XML.


    Take for example this common problem:

    How do I pass a PHP array to Javascript?

    PHP and Javascript can only communicate via strings. You can pass the string "foo" very easily to Javascript. You can pass the number 1 very easily to Javascript. You can pass the boolean values true and false easily to Javascript. But how do you pass this array to Javascript?

    Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 )

    The answer is serialization. In case of PHP/Javascript, JSON is actually the better serialization format:

    { 1 : 'elem 1', 2 : 'elem 2', 3 : 'elem 3' }

    Javascript can easily reverse this into an actual Javascript array.

    This is just as valid a representation of the same data structure though:

    a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}

    But pretty much only PHP uses it, there's little support for this format anywhere else.
    This is very common and well supported as well though:

    <array>
        <element key='1'>elem 1</element>
        <element key='2'>elem 2</element>
        <element key='3'>elem 3</element>
    </array>

    There are many situations where you need to pass complex data structures around as strings. Serialization, representing arbitrary data structures as strings, solves how to do this.

  • 相关阅读:
    【妖精眼镜】
    神兽保佑-代码无BUG
    Eclipse常用快捷键 及 不格式化注释
    Android dialog 全屏
    eclipse 改变颜色,背景
    GOOGLE和百度的长域名
    Android在ArrayAdapter<>里如何得到List<>的Items
    Android 仿微信朋友圈发动态功能(相册图片多选)
    Android 让GridView的高度为Wrap_content根据内容自适应高度
    C++中函数的返回值
  • 原文地址:https://www.cnblogs.com/oxspirt/p/6288442.html
Copyright © 2011-2022 走看看