• Reading a php array saved in a file

    The best way to save and read array in a file by “serialize” and “unserialize” method.

    Serialize: It generates a storable representation of a value.
    This is useful for storing or passing PHP values around without losing their type and structure.

    Unserialize: It takes a single serialized variable and converts it back into a PHP value.

    Code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
    <!--?php 
    $arr = array(
         'one'=-->array(
             'subdata1',
             'subdata2'
         ),
    );
    $string = serialize($arr);
    $fn= "serialtest.txt";
    $fh = fopen($fn, 'w');
    fwrite($fh, $string);
    fclose($fh);
     
    $str = file_get_contents('serialtest.txt');
    $arr = unserialize($str);
    print_r($arr);
    ?&gt;
    Output: Array ( [one] =&gt; Array ( [0] =&gt; subdata1 [1] =&gt; subdata2 ) )
    Tags:

Comments on this post

Leave a Reply

  • Security Code :


    + four = 5