【问题标题】:Send csv data with Guzzle as a chunked request使用 Guzzle 作为分块请求发送 csv 数据
【发布时间】:2016-09-06 14:42:21
【问题描述】:

我想将 CSV 数据上传到 REST API(仅在某个端点处除外 CSV 数据)。

CSV 数据的来源是用户上传的。上传的格式可以是 CVS、ODS 或 XLSX 电子表格数据。

当用户上传 CSV 文件时 - 我只是这样做(简化):

$handle = \fopen($tempFile, 'r');
$client->post('/import', ['body' => $handle]);

这很有效,而且很容易做到。但是,例如,当用户上传 XLSX 时,我目前会遍历第一张表中的行并使用 fputcsv 创建一个资源。

use Box\Spout\Reader\ReaderFactory;

$reader = ReaderFactory::create('xlsx');
$reader->open($tempFile);
$handle = \fopen('php://temp', 'r+');
/** @var $reader \Box\Spout\Reader\XLSX\Reader */
foreach ($reader->getSheetIterator() as $sheet) {
    /** @var $sheet \Box\Spout\Reader\XLSX\Sheet */
    foreach ($sheet->getRowIterator() as $row) {
        \fputcsv($handle, $row);
    }
    break;
}
$reader->close();
$client->post('/import', ['body' => $handle]);

我正在寻找一种在内存消耗和性能方面优化过程(XLSX 导入)的方法。

guzzle 是否可以在不先使用 fputcsv 创建完整资源的情况下将来自 foreach ($sheet->getRowIterator() as $row) 的请求作为分块请求发送?我希望这是有道理的。也许这甚至都不是优化...

【问题讨论】:

  • 这将与 Guzzle 6 一起使用吗?

标签: php rest http guzzle


【解决方案1】:

根据 GuzzleHttp 文档,该库使用 php 流:

http://docs.guzzlephp.org/en/latest/psr7.html#body

因此,您可以为您的请求创建一个流,然后使用 PSR7\StreamInteface 类中定义的write 方法逐行将内容写入其中:

https://github.com/php-fig/http-message/blob/master/src/StreamInterface.php#L115

顺便说一句,正如您在 Guzzle 文档中看到的那样,流本身使用 php://temp,就像您已经做的那样,只有优化,如果流大于 2MB,它将交换到磁盘以保留超出内存。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-07
    • 2017-08-28
    • 2020-07-14
    • 2019-12-12
    • 2020-03-28
    • 2015-08-12
    • 2018-03-21
    • 1970-01-01
    相关资源
    最近更新 更多