PHP关于数组缓存JSON、serialize、var_export的说明

1、JSON
JSON缓存变量主要是使用json_encode和json_decode函数,其中json_encode可以将变量变成文本格式存储到文件。

// Store cache
file_put_contents($cacheFilePath, json_encode($DataArray));
// Retrieve cache
$DataArray = json_decode(file_get_contents($cacheFilePath));

缺点:

只对UFT-8的数据有效,对stdClass类的示例有效;

2、serialize
序列化主要使用serialize和unserialize函数,都是以文本方式存储。

// Store cache
file_put_contents($cacheFilePath, serialize($DataArray));
// Retrieve cache
$DataArray = unserialize(file_get_contents($cacheFilePath));

缺点:

编码后的文本对人来说是不可读的,无法被其他语言的系统引用;

3、var_export
用var_export函数将变量内容打印到一个PHP文件(变量)里,使用include的方式来重新获取变量内容。因此生成的缓存文件时一个php文件。

// Store cache
file_put_contents($cacheFilePath, "<?php
return " . var_export($DataArray, true) . ";");
// Retrieve cache
$DataArray = include($cacheFilePath);

缺点:
不能缓存不带__set_state 方法的对象,var_export出来的变量里不能带有影响php语法解析的内容,否则触发语法错误。

总结:var_export在编码和解码的性能上不佳,建议在数据量小的时候使用序列化的方法。

原文地址:https://www.cnblogs.com/yudis/p/5611650.html