72

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

1

11 Answers 11

107

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

Sign up to request clarification or add additional context in comments.

4 Comments

your code is wrong. you won't retrieve an array with your code.
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.
if the array is average (500-2000 entries), then serializeand unserialize is actually a lot faster.
@Adam it depends on PHP version, see added benchmark in my answer.
45

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

4 Comments

Does the extension have to be bin?
Any extension is fine
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.
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.
25

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

3 Comments

How you can load that var_export() output again ? With eval() ? Try to var_export some Object.
Either with eval, or just simply include() the file.
Hm, I really don't see in what context would include alone work: I was trying for a while and failing, until I found stackoverflow.com/questions/933506/… - which confirms eval should be used for reading back var_exported data.
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
  );
?>

Comments

9

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

3 Comments

Just not to confuse someone I'd put DIC.php or something to make the difference with the var $dic
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)
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.
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.

Comments

1

Use php's serialze:

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

1 Comment

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.
0

This is an easy way to write one var to one file. Basically, you're creating a valid php file, to store and then including it, to retrieve.

// arraywritetofile('file.php','myvarName', array('pets'=>array('cow'=>'bessie','dog'=>'fido'));
 // thefile = path to file you want to write, $varname is the name your written file will have, $ra is the actual ra you are writing.
 // to read, just go include 'file.php'; and your $myvarName will be in the scope.
    function arraywritetofile($thefile, $varname, $ra){
        $ra    = var_export($ra, true);
        $write = '<?php
            $'.$varname.' =
            '.$ra.';
            ?>';
        
        $put = file_put_contents($thefile, $write);
        //echo "<pre>".htmlentities($write)."</pre>";
        
    }//  func

Comments

0

Use serialize and unserialize

$data = ["name" => "John", "age" => 30, "city" => "New York"];
$file = '/data_folder/data.txt';

// save data
file_put_contents($file, serialize($data));
//a:3:{s:4:"name";s:4:"John";s:3:"age";i:30;s:4:"city";s:8:"New York";} 

// get data
$data = unserialize(file_get_contents($file));

Serialize:

  • Format: Outputs a specialized serialized format.
  • Use Case: Commonly used in PHP to serialize complex data structures (arrays, objects) for storage in a file or a database.
  • Data Types: Supports a wider range of data types compared to JSON, including objects, resources, and more.
  • Readability: Serialized data is not human-readable, and it's generally meant to be used within PHP applications.

Serialize vs. Json

  • If you need to exchange data between different programming languages or platforms, JSON is a more universal choice.

  • If the data is only meant to be used within a PHP application and you need to preserve the exact state of objects, serialize might be more suitable.

  • JSON is often preferred for data interchange due to its simplicity, readability, and widespread support.

Choose between json_encode and serialize based on your specific use case and the requirements of your application.

json_encode:

$data = ["name" => "John", "age" => 30, "city" => "New York"];
$file = '/data_folder/data.txt';

// save data
file_put_contents($file,json_encode($data));
// {"name":"John","age":30,"city":"New York"}

// get data
$data = json_decode(file_get_contents('$file'), true);
  • Format: Outputs data in JSON format.
  • Use Case: Primarily used for encoding data to be sent between a server and a web application, or for storing configuration settings.
  • Data Types: Supports a limited set of data types: strings, numbers, arrays, objects, booleans, and null.
  • Readability: JSON is human-readable and widely supported by various programming languages.

1 Comment

in my case, although my application is entirely in php, i am still using json because i want to easily read the text file so i am going for json
0

Using json_encode/decode changes the array to an object.

So use serialize/unserialize instead.

// Define file path
$file = 'filename.php';

// Store array to a file
file_put_contents($file, serialize($array));

// Retrieve array from a file
$array = unserialize(file_get_contents($file));

Comments

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

2 Comments

Could you please explain, what makes this a better choice than already existing language serialization/storage facilities?
Hi, this looks handy. Is it still around? THe link is broke.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.