70

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.
  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 store_array() or restore_arrray() ?!

Rubens Mariuzzo
  • 28,358
  • 27
  • 121
  • 148
Haroldo
  • 36,607
  • 46
  • 127
  • 169
  • 3
    Main differences bettwen JSON and binary serialize functions are mentioned here - http://stackoverflow.com/questions/804045/preferred-method-to-store-php-arrays-json-encode-vs-serialize/804089#804089. – retro Apr 18 '10 at 14:19

8 Answers8

106

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);
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).

Community
  • 1
  • 1
retro
  • 3,765
  • 2
  • 20
  • 37
  • 3
    your code is wrong. you won't retrieve an array with your code. – Tor Valamo Apr 18 '10 at 16:22
  • 1
    There is type mismatch on second line. There should be $arr1. Also you need to pass true as second parameter to json_decode to return array. Code updated. – retro Apr 18 '10 at 16:33
  • 2
    if the array is average (500-2000 entries), then `serialize`and `unserialize` is actually a lot faster. – Adam Aug 12 '16 at 07:05
  • @Adam it depends on PHP version, see added benchmark in my answer. – retro Sep 07 '16 at 14:13
42

If you don't need the dump file to be human-readable, you can just serialize() the array.

storing:

file_put_contents('yourfile.bin', serialize($array));

retrieving:

$array = unserialize(file_get_contents('yourfile.bin'));
soulmerge
  • 73,842
  • 19
  • 118
  • 155
  • 1
    Does the extension have to be bin? – user4951 Aug 11 '16 at 10:21
  • 1
    Any extension is fine – mt025 Aug 21 '16 at 01:12
  • This example seems to be secure. But sometimes calling unserialize on user input can be dangerous as it allows an attacker to define any variable with an arbitrary value. – Adam Lindsay Jan 01 '17 at 14:51
  • 1
    There is no way you would know if it is secure or not @AdamLindsay since the array could (is likely to be) user supplied data. Look up PHP object injection. unserialize() takes a second parameter to restrict the classes which can be loaded in serialised objects... setting this value to FALSE provides additional security. – hiburn8 Jul 04 '19 at 14:07
24

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) . ';');
K. Norbert
  • 10,494
  • 5
  • 49
  • 48
  • How you can load that var_export() output again ? With eval() ? Try to var_export some Object. – retro Apr 18 '10 at 16:46
  • Either with eval, or just simply include() the file. – K. Norbert Apr 18 '10 at 18:03
  • Hm, I really don't see in what context would `include` alone work: I was trying for a while and failing, until I found http://stackoverflow.com/questions/933506/how-to-read-output-of-var-export-into-a-variable-in-php - which confirms `eval` should be used for reading back `var_export`ed data. – sdaau Jul 05 '15 at 14:21
14

Another fast way not mentioned here:

That way add header with <?php start tag, name of variable \$my_array = with escaped \$ and footer ?> end tag.

Now can use include() like any other valid php script.

<?php
  // storing
  $file = '/tmp/out.php';
  $var = ['a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5];

  file_put_contents($file,
    "<?php\n\$my_array = "
      .var_export($var, true)
    .";\n?>"
  );

  // retrieving as included script
  include($file);

  //testing
  print_r($my_array);
?>

out.php will look like this

<?php
  $my_array = array (
    'a'=>1,
    'b'=>2,
    'c'=>3,
    'd'=>4,
    'e'=>5
  );
?>
MTK
  • 3,300
  • 2
  • 33
  • 49
8

You can use serialize to make it into a string to write to file, and the accompanying unserialize to return it to an array structure.

I'd suggest using a language independent structure though, such as JSON. This will allow you to load the files using different languages than PHP, in case there's a chance of that later. json_encode to store it and json_decode($str, true) to return it.

Tor Valamo
  • 33,261
  • 11
  • 73
  • 81
6

Talking about php use, for performance sake, avoid encoding and decoding everything, just save array with:

file_put_contents('dic.php', "<?php return " . var_export($dic, true) . ";\n");

and call normally with

$dic = include "dic.php";

Reference: https://php.net/include

hakre
  • 193,403
  • 52
  • 435
  • 836
Nik Drosakis
  • 2,258
  • 21
  • 30
  • 1
    Just not to confuse someone I'd put DIC.php or something to make the difference with the var $dic – dstonek Jan 22 '20 at 21:37
  • 1
    Just for those wondering; including a file that contains a PHP array like this, is faster than unseralizing the content of a file containing a serialized PHP array (like some of the other comments suggest) – Albert MN. May 13 '21 at 14:25
  • Yes, this is faster than unserializing and no need to call json_decode(). when using the return statement, anonymous (fixed that in the answer /cc @dstonek) and in case the file does not exists, the result is `FALSE`, which is not an array or never an empty one. – hakre Jul 01 '23 at 19:26
1

Use php's serialze:

file_put_contents("myFile",serialize($myArray));
elias
  • 1,481
  • 7
  • 13
  • 1
    Since there is "no need for efficiency", this is the last choice I would recommend. It may be easy to code a solution with serialize/unserialize, but the array is not in a very readable/editable format if people actually want to view or modify the stored file. Further, if stored in a repository, all data is on one line, so small changes to larger arrays are very hard to see. – Lowell Montgomery Aug 13 '14 at 09:12
-1

I made a tiny library (~2 KB; <100 lines) that allows you to do just this: varDx

It has functions to write, read, modify, check and delete data. It implements serialization, and therefore supports all data types.

Here's how you can use it:

<?php
require 'varDx.php';
$dx = new \varDx\cDX; //create an object
$dx->def('file.dat'); //define data file

$val1 = "this is a string";
$dx->write('data1', $val1); //writes key to file
echo $dx->read('data1'); //returns key value from file

In your specific case:

$array1 = array(
    "foo" => "bar",
    "bar" => "foo",
);

//writing the array to file
$dx->write('myarray', $array1);

//reading array from file
$array2 = $dx->read('myarray')

//modifying array in file after making changes
$dx->write('myarray', $array2);
undo
  • 257
  • 3
  • 19