2014-09-24 82 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); 
}