2014-09-24 77 views
1

我正在使用flysystem與IRON IO隊列,我試圖運行一個數據庫查詢,將採取約180萬條記錄,同時做5000個。這裏是我用的50 + MB文件大小收到錯誤消息:phpleague flysystem讀取和寫入服務器上的大文件

PHP Fatal error: Allowed memory size of ########## bytes exhausted 

下面是我想採取的步驟:

1)獲取數據

2)打開它成CSV適當的字符串(即implode(',', $dataArray) . "\r\n"

3)從服務器獲取的文件(在這種情況下,S3)

4)閱讀文件的內容,並追加新〜應變g到它,並重新編寫內容到S3文件

這裏是一個簡短的代碼運行下來,我有:

public function fire($job, $data) 
{ 
    // First set the headers and write the initial file to server 
    $this->filesystem->write($this->filename, implode(',', $this->setHeaders($parameters)) . "\r\n", [ 
     'visibility' => 'public', 
     'mimetype' => 'text/csv', 
    ]); 

    // Loop to get new sets of data 
    $offset = 0; 

    while ($this->exportResult) { 
     $this->exportResult = $this->getData($parameters, $offset); 

     if ($this->exportResult) { 
      $this->writeToFile($this->exportResult); 

      $offset += 5000; 
     } 
    } 
} 

private function writeToFile($contentToBeAdded = '') 
{ 
    $content = $this->filesystem->read($this->filename); 

    // Append new data 
    $content .= $contentToBeAdded; 

    $this->filesystem->update($this->filename, $content, [ 
     'visibility' => 'public' 
    ]); 
} 

我猜想這是不是最有效的?我要走這些文檔: PHPLeague Flysystem

如果任何人都可以指出我在一個更合適的方向,這將是太棒了!

+0

有什麼辦法將追加到使用Flysystem文件?否則,我不知道如何避免使用這麼多的內存。 – andy 2014-09-24 15:24:49

+0

@andy不,它看起來不像。他們有一個流功能,但我認爲這與您必須閱讀該文件以更新其內容的方式相同。 – 2014-09-24 15:57:30

回答

1

如果您使用S3,我將直接使用適用於PHP的AWS開發工具包來解決此特定問題。使用SDK的S3 streamwrapper添加文件實際上非常簡單,並且不會強制您將整個文件讀入內存。

$s3 = \Aws\S3\S3Client::factory($clientConfig); 
$s3->registerStreamWrapper(); 

$appendHandle = fopen("s3://{$bucket}/{$key}", 'a'); 
fwrite($appendHandle, $data); 
fclose($appendHandle); 
0

Flysystem支持讀/寫/更新流

請查看最新的API https://flysystem.thephpleague.com/api/

$stream = fopen('/path/to/database.backup', 'r+'); 
$filesystem->writeStream('backups/'.strftime('%G-%m-%d').'.backup', $stream); 

// Using write you can also directly set the visibility 
$filesystem->writeStream('backups/'.strftime('%G-%m-%d').'.backup', $stream, [ 
    'visibility' => AdapterInterface::VISIBILITY_PRIVATE 
]); 

if (is_resource($stream)) { 
    fclose($stream); 
} 

// Or update a file with stream contents 
$filesystem->updateStream('backups/'.strftime('%G-%m-%d').'.backup', $stream); 

// Retrieve a read-stream 
$stream = $filesystem->readStream('something/is/here.ext'); 
$contents = stream_get_contents($stream); 
fclose($stream); 

// Create or overwrite using a stream. 
$putStream = tmpfile(); 
fwrite($putStream, $contents); 
rewind($putStream); 
$filesystem->putStream('somewhere/here.txt', $putStream); 

if (is_resource($putStream)) { 
    fclose($putStream); 
}