如何将数组存储在文件中以便稍后使用 PHP 作为数组访问?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2662268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I store an array in a file to access as an array later with PHP?
提问by Haroldo
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 获取的数组,以便我可以在本地主机上处理它。
So:
所以:
- I currently have an array.
- I want to people to use the array without having to get it from the API.
- 我目前有一个数组。
- 我想让人们使用该数组而不必从 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()?!
有没有类似store_array()或的功能restore_arrray()?!
回答by retro
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 序列化。它是人类可读的,您将获得更好的性能(文件更小,加载/保存速度更快)。代码非常简单。只有两个功能
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.
您可以使用此示例轻松编写自己的 store_array 和 restore_array 函数。
For speed comparison see benchmarkoriginally from Preferred method to store PHP arrays (json_encode vs serialize).
有关速度比较,请参阅最初来自Preferred method to store PHP array (json_encode vs serialize) 的基准测试。
回答by soulmerge
If you don't need the dump file to be human-readable, you can just serialize()the array.
如果您不需要转储文件是人类可读的,您可以只serialize()使用数组。
storing:
存储:
file_put_contents('yourfile.bin', serialize($array));
retrieving:
检索:
$array = unserialize(file_get_contents('yourfile.bin'));
回答by K. Norbert
Use serializeand 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_contentsto store it on disk, and use file_get_contentsand evalto read it back.
var_export()完全符合您的要求,它将接受任何类型的变量,并将其存储在 PHP 解析器可以读回的表示中。您可以将其与file_put_contents组合以将其存储在磁盘上,并使用file_get_contents和eval将其读回。
// storing
$file = '/tmp/out.php';
file_put_contents($file, var_export($var, true));
// retrieving
eval('$myvar = ' . file_get_contents($file) . ';');
回答by MTK
Another fast way not mentioned here:
此处未提及的另一种快速方法:
That way add header with <?phpstart tag, name of variable \$my_array =with escaped \$and footer ?>end tag.
这样添加带有<?php开始标签的标题,\$my_array =带有转义\$和页脚?>结束标签的变量名称。
Now can use include()like any other valid php script.
现在可以include()像任何其他有效的 php 脚本一样使用。
// storing
$file = '/tmp/out.php';
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
out.php 看起来像这样
<?php
$my_array = array (
'a'=>1,
'b'=>2,
'c'=>3,
'd'=>4,
'e'=>5
);
?>
回答by Tor Valamo
You can use serializeto make it into a string to write to file, and the accompanying unserializeto return it to an array structure.
您可以使用serialize将其变成字符串以写入文件,并使用随附的反序列化将其返回为数组结构。
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_encodeto store it and json_decode($str, true)to return it.
不过,我建议使用独立于语言的结构,例如 JSON。这将允许您使用与 PHP 不同的语言加载文件,以防以后有可能。json_encode来存储它,json_decode($str, true)来返回它。
回答by Nik Drosakis
Talking about php use, for performance sake, avoid encoding and decoding everything, just save array with:
说到 php 的使用,为了性能考虑,避免编码和解码一切,只需保存数组:
file_put_contents('dic.php', "<?php \n".'$dic='.var_export($dic, true).';');
and call normally with
并正常调用
include "dic.php";
回答by elias
Use php's serialze:
使用 php 的序列化:
file_put_contents("myFile",serialize($myArray));
回答by undo
I made a tiny library (~2 KB; <100 lines) that allows you to do just this: varDx
我制作了一个小库(~2 KB;<100 行),可以让你做到这一点: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);

