serialize a large array in PHP?

前端 未结 13 1945
死守一世寂寞
死守一世寂寞 2021-01-04 06:11

I am curious, is there a size limit on serialize in PHP. Would it be possible to serialize an array with 5,000 keys and values so it can be stored into a cache?

I am

相关标签:
13条回答
  • 2021-01-04 06:42

    The only practical limit is your available memory, since serialization involves creating a string in memory.

    0 讨论(0)
  • 2021-01-04 06:42

    Your use case sounds like you're better off using a database to do that rather than relying solely on PHP's available resources. The advantages to using something like MySQL instead is that it's specifically engineered with memory management in mind for such things as storage and lookup.

    It's really no fun constantly serializing and unserializing data just to update or change a few pieces of information.

    0 讨论(0)
  • 2021-01-04 06:44

    There is no limit, but remember that serialization and unserialization has a cost.

    Unserialization is exteremely costly.

    A less costly way of caching that data would be via var_export() as such (since PHP 5.1.0, it works on objects):

    $largeArray = array(1,2,3,'hello'=>'world',4);
    
    file_put_contents('cache.php', "<?php\nreturn ".
                                    var_export($largeArray, true).
                                    ';');
    

    You can then simply retrieve the array by doing the following:

    $largeArray = include('cache.php');
    

    Resources are usually not cache-able.

    Unfortunately, if you have circular references in your array, you'll need to use serialize().

    0 讨论(0)
  • 2021-01-04 06:46

    Nope, there is no limit and this:

    set_time_limit(0);
    ini_set('memory_limit ', -1);
    
    unserialize('s:2000000000:"a";');
    

    is why you should have safe.mode = On or a extension like Suhosin installed, otherwise it will eat up all the memory in your system.

    0 讨论(0)
  • 2021-01-04 06:48

    i have a case in which unserialize throws an exception on a large serialized object, size: 65535 (the magic number: 16bits full bit = 65536)

    0 讨论(0)
  • 2021-01-04 06:49

    As suggested by Thinker above:

    You could use

    $string = json_encode($your_array_here);
    

    and to decode it

    $array = json_decode($your_array_here, true);
    

    This returns an array. It works well even if the encoded array was multilevel.

    0 讨论(0)
提交回复
热议问题