How to deal with memory leak when exporting data?

I export to CSV relative to dataProvider. But it turns out that at some point on a complex view (more than 10 join) it crashes with an error about the lack of PDO memory.

private function writeContentRowsQuery() {
    $offset = 0;
    
    while ($queryResult = $this->dataProvider->query->limit($this->_settings['limit'])->offset($offset)->createCommand()->queryAll()) {
        foreach ($queryResult as $row) {
            $rowData = [];
            
            foreach ($this->_visibleColumns as $visibleColumn) {
                $rowData[] = $this->getDataCellQueryValue($visibleColumn, $row);
            }
            
            fputcsv($this->_csv, $rowData, ';');
            ob_flush();
            flush();
            
            unset($rowData);
            gc_collect_cycles();
        }
        
        $offset += $this->_settings['limit'];
        
        unset($queryResult);
        gc_collect_cycles();
    }
    
    gc_collect_cycles();
}

Calling from:

ob_start();
$this->_csv = fopen('php://output', 'wb');

if (!empty($this->contentBefore)) {
    $this->writeBeforeContentRows();
}

$this->writeColumnHeaders();
$this->writeContentRowsQuery();
fclose($this->_csv);

What to do in this case?

Errors: PDOException: SQLSTATE [54000]: Program limit exceeded: 7 ERROR: Out of memory DETAIL: Failed to increase string buffer

Shouts at the lines:

  1. ob_flush(); that Headers already sent
  2. while ($queryResult = $this->dataProvider->query->limit($this->_ settings['limit'])->offset($offset)->createCommand()->queryAll()) about out of memory

See https://github.com/yiisoft/yii2/issues/8420