简体   繁体   English

用PHP将数组保存到磁盘的最快方法是什么?

[英]What is the quickest way to save an array to disk in PHP?

I'd like to save an array to disk so that I can easily read it back into an array. 我想将阵列保存到磁盘,以便可以轻松地将其读回到阵列中。 What would be an easy way to do this? 有什么简单的方法可以做到这一点?

file_put_contents($file, serialize($array));

And read it back by 然后读回来

$array = unserialize(file_get_contents($file));

Edit: You can also use json_encode/json_decode instead. 编辑:您也可以改用json_encode / json_decode。 Check this question Preferred method to store PHP arrays (json_encode vs serialize) to get more information. 检查此问题首选方法存储PHP数组(json_encode与序列化)以获取更多信息。

One issue is that serialize() is not guaranteed to be portable between different applications - it's ONLY designed to be readable by PHP. 一个问题是,不能保证serialize()可以在不同应用程序之间移植-仅设计为PHP可以读取。 PHP don't even guarantee that it will be portable between different PHP versions. PHP甚至不保证它可以在不同的PHP版本之间移植。

Therefore, serialize() is great for local temporary data because it's fast, but if you want something to be more permanent, and highly portable, I'd use json_encode() . 因此, serialize()非常适合本地临时数据,因为它的速度很快,但是如果您希望某些东西更永久且高度可移植,则可以使用json_encode()

Then use json_decode() , obviously, to decode it. 然后显然使用json_decode()对其进行解码。

有关JSON,序列化和var_export三种方法的基准测试,请参阅http://techblog.procurios.nl JSON可能最适合大型(> 50 Mb)阵列,尽管它仅适用于UTF-8编码数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM