Haroldo Haroldo - 1 year ago 81
PHP Question

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

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.


  1. I currently have an array.

  2. I want to people to use the array without having to get it from the API.

There are no needs for efficiency etc here, this isnt for an actual site just for getting some sanitizing/formatting methods made etc

Is there a function like

Answer Source

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

Example code:

$arr1 = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
# 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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download