相信很多人做大批量資料匯出和資料匯入的時候,經常會遇到PHP記憶體溢位的問題,在解決了問題之后,總結了一些經驗,整理成文章記錄下,
優化點
- 優化SQL陳述句,避免慢查詢,合理的建立索引,查詢指定的欄位,sql優化這塊在此就不展開了,
- 查詢的結果集為大物件時轉陣列處理,框架中一般有方法可以轉,如Laravel中有toArray(),Yii2中有asArray(),
- 對于大陣列進行資料切割處理,PHP函式有array_chunk()、array_slice(),
- 對于大型的字串和物件,使用參考傳遞&,
- 用過的變數及時unset,
- 匯出的檔案格式由excel改為csv
- ini_set('memory_limit',''),設定程式可以使用的記憶體(不建議這樣做),
思考
記憶體管理
PHP的記憶體什么怎么管理的呢? 在學C語言時,開發者是需要手動管理記憶體,在PHP中,Zend引擎提供為了處理請求相關資料提供了一種特殊的記憶體管理器,請求相關資料是只需要服務單個請求,最遲會在請求結束時釋放資料,

防止記憶體泄漏并盡可能快地釋放所有記憶體是記憶體管理的重要組成部分,因為安全原因,Zend引擎會釋放所有上面提到的API鎖分配的記憶體,
垃圾回識訓制
簡單說下:
PHP5.3之前,采用參考計數的方式管理,PHP中的變數存在zval的變數容器中,變數被參考的時,參考計數+1,變數參考計數為0時,PHP將在記憶體中銷毀這個變數,但是在參考計數回圈參考時,參考計數就不會消減為0,導致記憶體泄漏,
PHP5.3之后做了優化,并不是每次參考計數減少都進入回收周期,只有根緩沖區滿額后才開始進行垃圾回收,這樣可以解決回圈參考的問題,也可以將總記憶體泄漏保持在一個閾值之下,
代碼
由于使用phpexcel時經常會遇到記憶體溢位,下面分享一段生成csv檔案的代碼:
<?php
namespace api\service;
class ExportService
{
public static $outPutFile = '';
/**
* 匯出檔案
* @param string $fileName
* @param $data
* @param array $formFields
* @return mixed
*/
public static function exportData($fileName = '', $data, $formFields = [])
{
$fileArr = [];
$tmpPath = \Yii::$app->params['excelSavePath'];
foreach (array_chunk($data, 10000) as $key => $value) {
self::$outPutFile = '';
$subject = !empty($fileName) ? $fileName : 'data_';
$subject .= date('YmdHis');
if (empty($value) || empty($formFields)) {
continue;
}
self::$outPutFile = $tmpPath . $subject . $key . '.csv';
if (!file_exists(self::$outPutFile)) {
touch(self::$outPutFile);
}
$index = array_keys($formFields);
$header = array_values($formFields);
self::outPut($header);
foreach ($value as $k => $v) {
$tmpData = https://www.cnblogs.com/uuuuu55/p/[];
foreach ($index as $item) {
$tmpData[] = isset($v[$item]) ? $v[$item] : '';
}
self::outPut($tmpData);
}
$fileArr[] = self::$outPutFile;
}
$zipFile = $tmpPath . $fileName . date('YmdHi') . '.zip';
$zipRes = self::zipFile($fileArr, $zipFile);
return $zipRes;
}
/**
* 向檔案寫入資料
* @param array $data
*/
public static function outPut($data = https://www.cnblogs.com/uuuuu55/p/[])
{
if (is_array($data) && !empty($data)) {
$data = https://www.cnblogs.com/uuuuu55/p/implode(',', $data);
file_put_contents(self::$outPutFile, iconv("UTF-8", "GB2312//IGNORE", $data) . PHP_EOL, FILE_APPEND);
}
}
/**
* 壓縮檔案
* @param $sourceFile
* @param $distFile
* @return mixed
*/
public static function zipFile($sourceFile, $distFile)
{
$zip = new \ZipArchive();
if ($zip->open($distFile, \ZipArchive::CREATE) !== true) {
return $sourceFile;
}
$zip->open($distFile, \ZipArchive::CREATE);
foreach ($sourceFile as $file) {
$fileContent = file_get_contents($file);
$file = iconv('utf-8', 'GBK', basename($file));
$zip->addFromString($file, $fileContent);
}
$zip->close();
return $distFile;
}
/**
* 下載檔案
* @param $filePath
* @param $fileName
*/
public static function download($filePath, $fileName)
{
if (!file_exists($filePath . $fileName)) {
header('HTTP/1.1 404 NOT FOUND');
} else {
//以只讀和二進制模式打開檔案
$file = fopen($filePath . $fileName, "rb");
//告訴瀏覽器這是一個檔案流格式的檔案
Header("Content-type: application/octet-stream");
//請求范圍的度量單位
Header("Accept-Ranges: bytes");
//Content-Length是指定包含于請求或回應中資料的位元組長度
Header("Accept-Length: " . filesize($filePath . $fileName));
//用來告訴瀏覽器,檔案是可以當做附件被下載,下載后的檔案名稱為$file_name該變數的值
Header("Content-Disposition: attachment; filename=" . $fileName);
//讀取檔案內容并直接輸出到瀏覽器
echo fread($file, filesize($filePath . $fileName));
fclose($file);
exit();
}
}
}
呼叫處代碼
$fileName = "庫存匯入模板";
$stockRes = []; // 匯出的資料
$formFields = [
'store_id' => '門店ID',
'storeName' => '門店名稱',
'sku' => 'SKU編碼',
'name' => 'SKU名稱',
'stock' => '庫存',
'reason' => '原因'
];
$fileRes = ExportService::exportData($fileName, $stockRes, $formFields);
$tmpPath = \Yii::$app->params['excelSavePath']; // 檔案路徑
$fileName = str_replace($tmpPath, '', $fileRes);
// 下載檔案
ExportService::download($tmpPath, $fileName);
以上內容希望幫助到大家,更多PHP大廠PDF面試檔案,PHP進階架構視頻資料,PHP精彩好文免費獲取可以微信搜索關注公眾號:PHP開源社區,或者訪問:
2021金三銀四大廠面試真題集錦,必看!
四年精華PHP技術文章整理合集——PHP框架篇
四年精華PHP技術文合集——微服務架構篇
四年精華PHP技術文合集——分布式架構篇
四年精華PHP技術文合集——高并發場景篇
四年精華PHP技術文章整理合集——資料庫篇
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/263203.html
標籤:PHP
上一篇:關于PHP的方法引數型別約束
下一篇:Python語言系列文章總結
