如何将数组存储在文件中,以便以后使用PHP作为数组访问? [英] How do I store an array in a file to access as an array later with PHP?
问题描述
我只想快速存储一个从远程API获取的数组,以便可以在本地主机上处理它.
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.
所以:
- 我目前有一个数组.
- 我希望人们不必从API获取数组就可以使用它.
这里不需要效率等,这不是实际站点的目的,只是为了获得一些消毒/格式化方法等
There are no needs for efficiency etc here, this isnt for an actual site just for getting some sanitizing/formatting methods made etc
是否有类似 store_array()
或 restore_arrray()
的功能?!
Is there a function like store_array()
or restore_arrray()
?!
推荐答案
做到这一点的最佳方法是JSON序列化.它是人类可读的,您将获得更好的性能(文件更小,加载/保存更快).代码很简单.只有两个功能
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
- json_encode
- json_decode
示例代码:
$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
通过此示例,您可以轻松编写自己的store_array和restore_array函数.
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).
这篇关于如何将数组存储在文件中,以便以后使用PHP作为数组访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!