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

前端 未结 8 1353
粉色の甜心
粉色の甜心 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条回答
  •  既然无缘
    2020-12-02 14:31

    Use serialize and unserialize

    // storing
    $file = '/tmp/out.data';
    file_put_contents($file, serialize($mydata)); // $mydata is the response from your remote API
    
    // retreiving
    $var = unserialize(file_get_contents($file));
    

    Or another, hacky way:

    var_export() does exactly what you want, it will take any kind of variable, and store it in a representation that the PHP parser can read back. You can combine it with file_put_contents to store it on disk, and use file_get_contents and eval to read it back.

    // storing
    $file = '/tmp/out.php';
    file_put_contents($file, var_export($var, true));
    
    // retrieving
    eval('$myvar = ' . file_get_contents($file) . ';');
    

提交回复
热议问题