How do I store an array in a file to access as an array later with PHP?

前端 未结 8 1347
粉色の甜心
粉色の甜心 2020-12-02 14:17

I just want to quickly store an array which I get from a remote API, so that i can mess around with it on a local host.

So:

  1. I currently have an array.<
8条回答
  •  -上瘾入骨i
    2020-12-02 14:36

    The best way to do this is JSON serializing. It is human readable and you'll get better performance (file is smaller and faster to load/save). The code is very easy. Just two functions

    • json_encode
    • json_decode

    Example code:

    $arr1 = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
    file_put_contents("array.json",json_encode($arr1));
    # array.json => {"a":1,"b":2,"c":3,"d":4,"e":5}
    $arr2 = json_decode(file_get_contents('array.json'), true);
    $arr1 === $arr2 # => true
    

    You can write your own store_array and restore_array functions easily with this example.

    For speed comparison see benchmark originally from Preferred method to store PHP arrays (json_encode vs serialize).

提交回复
热议问题