迴圈一個檔案夾下的 txt 檔案,將其中資料按行讀取存進資料庫 出現 Fatal error: Allowed memory size of 134217728 bytes exhausted 的錯誤提示,
代碼如下,我每一個 txt 檔案都不大(100k左右),而且是按行進行讀取的,原因在哪呢?
$file = new \FilesystemIterator($fileName); foreach ($file as $fileinfo) { if ( $fileinfo->isFile() ) { $fp = fopen($fileName . '/' . $fileinfo->getFilename(), 'r'); while(! feof($fp)) { $data['score'] = 7; $data['code'] = fgets($fp); $this->book->add($data);//存進資料庫 } fclose($fp); } }
回複內容:
迴圈一個檔案夾下的 txt 檔案,將其中資料按行讀取存進資料庫 出現 Fatal error: Allowed memory size of 134217728 bytes exhausted 的錯誤提示,
代碼如下,我每一個 txt 檔案都不大(100k左右),而且是按行進行讀取的,原因在哪呢?
$file = new \FilesystemIterator($fileName); foreach ($file as $fileinfo) { if ( $fileinfo->isFile() ) { $fp = fopen($fileName . '/' . $fileinfo->getFilename(), 'r'); while(! feof($fp)) { $data['score'] = 7; $data['code'] = fgets($fp); $this->book->add($data);//存進資料庫 } fclose($fp); } }
用關鍵字yield 進行迭代操作,不會儲存中間變數節省記憶體,要求php5.5+
$this->book->add($data);
unset($data);
while迴圈時$data會發生寫時複製(COW),這些記憶體只有在你的指令碼執行結束後才會釋放
安裝xdebug或者xhprof查看效能分析報告。
我估計是架構的配置,sql做了收集