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

Php

Php Problem Overview


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() ?!

Php Solutions


Solution 1 - Php

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 https://stackoverflow.com/questions/804045/preferred-method-to-store-php-arrays-json-encode-vs-serialize/804089#804089.

Solution 2 - Php

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

Solution 3 - Php

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

Solution 4 - Php

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

Solution 5 - Php

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.

Solution 6 - Php

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

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

and call normally with

include "dic.php";

Solution 7 - Php

Use php's serialze:

file_put_contents("myFile",serialize($myArray));

Solution 8 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHaroldoView Question on Stackoverflow
Solution 1 - PhpretroView Answer on Stackoverflow
Solution 2 - PhpsoulmergeView Answer on Stackoverflow
Solution 3 - PhpK. NorbertView Answer on Stackoverflow
Solution 4 - PhpMTKView Answer on Stackoverflow
Solution 5 - PhpTor ValamoView Answer on Stackoverflow
Solution 6 - PhpNik DrosakisView Answer on Stackoverflow
Solution 7 - PhpeliasView Answer on Stackoverflow
Solution 8 - PhpundoView Answer on Stackoverflow