可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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:
- I currently have an array.
- 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:
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).
回答2:
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'));
回答3:
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) . ';');
回答4:
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.
回答5:
Use php's serialze:
file_put_contents("myFile",serialize($myArray));
回答6:
Another fast way not mentioned here:
That way add header with start tag, name of variable \$my_array =
with escaped \$
and footer ?>
end tag.
Now can use include()
like any other valid php script.
// storing $file = '/tmp/out.php'; file_put_contents($file, ""); // retrieving as included script include($file); //testing print_r($my_array);
out.php will look like this
1, 'b'=>2, 'c'=>3, 'd'=>4, 'e'=>5 ); ?>