我只想快速存储一个从远程API获取的数组,这样我就可以在本地主机上乱搞它.
所以:
这里没有效率等需求,这对于实际网站来说只是为了获得一些消毒/格式化方法等
有没有像?store_array()或restore_arrray()!的功能!
ret*_*tro 80
执行此操作的最佳方法是JSON序列化.它是人类可读的,你将获得更好的性能(文件更小,加载/保存更快).代码非常简单.只是两个功能
示例代码:
$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
Run Code Online (Sandbox Code Playgroud)
您可以使用此示例轻松编写自己的store_array和restore_array函数.
对于速度比较,请参阅最初从Preferred方法存储PHP数组的基准(json_encode vs serialize).
sou*_*rge 32
如果您不需要转储文件是人类可读的,那么您可以只serialize()使用数组.
存储:
file_put_contents('yourfile.bin', serialize($array));
Run Code Online (Sandbox Code Playgroud)
检索:
$array = unserialize(file_get_contents('yourfile.bin'));
Run Code Online (Sandbox Code Playgroud)
K. *_*ert 21
// 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));
Run Code Online (Sandbox Code Playgroud)
或另一种黑客方式:
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) . ';');
Run Code Online (Sandbox Code Playgroud)
您可以使用serialize将其转换为要写入文件的字符串,并使用随附的unserialize将其返回到数组结构.
我建议使用与语言无关的结构,例如JSON.这将允许您使用与PHP不同的语言加载文件,以防以后有可能.json_encode存储它和json_decode($str, true)返回它.
这里没有提到的另一种快速方法:
这样,可以添加带有<?php开始标记的标头,\$my_array =带有转义的变量名称\$和页脚?>结束标记。
现在可以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);
Run Code Online (Sandbox Code Playgroud)
out.php看起来像这样
<?php
$my_array = array (
'a'=>1,
'b'=>2,
'c'=>3,
'd'=>4,
'e'=>5
);
?>
Run Code Online (Sandbox Code Playgroud)
说到 php 的使用,为了性能考虑,避免编码和解码一切,只需保存数组:
file_put_contents('dic.php', "<?php \n".'$dic='.var_export($dic, true).';');
Run Code Online (Sandbox Code Playgroud)
并正常调用
include "dic.php";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
71398 次 |
| 最近记录: |