使用phpspreadsheet进行导出excel的时候遇到了内存溢出的问题,官方提供了memory saving的解决方案,官方文档中提供了APCu、redis和memcache的缓存方案,但是在这些缓存方案都需要安装相应的扩展并且都为内存型缓存,数据量一大的话就会大大占用系统的内存,可能会影响项目的正常运行的,于是就自行实现了一种文件缓存的方式,实测可以减少导excel表时一半的内存使用量,在此把代码贴在下面记录一下。
//调用示例 在实例化spreadersheet对象前设置
\PhpOffice\PhpSpreadsheet\Settings::setCache(new \Excel\FileCache('/tmp/excel_cache'));
<?php
namespace Excel;
use Psr\SimpleCache\CacheInterface;
class FileCache implements CacheInterface {
const FILE_SIZE = 3000; //读取时单次缓存行数(文件分割行数)
private $cache_key = [];
private $cache = [], $file_handles = [], $cache_dir, $file_prefix;
private function delCacheDir($path) {
if (is_dir($path)) {
foreach (scandir($path) as $val) {
if ($val != "." && $va