首页 > 解决方案 > 在 Guzzle 中使用 `sink` 选项下载文件会导致空文件。为什么?以及如何解决?

问题描述

我需要使用 Guzzle 下载文件。目前我使用的是 6.3.3 版本。

我将sink选项传递给我的请求,但尽管我请求的 API 响应带有一些正文内容的“200 OK”,但目标文件始终为空。

这是我到目前为止的代码:

// sidenote:
// $this->importFile is the absolute path to the file the contents have to be downloaded to
// $this->api is a GuzzleHttp\Client, base URL has been set previously
// $uri is the API endpoint's URI I am requesting (like "get/data")
// $this->getQueryParams() returns an array with a few needed parameters

$downloadDestination = fopen($this->importFile, 'w');

$response = $this->api->get($uri, [
    'query' => $this->getQueryParams(),
    'sink' => $downloadDestination,
]);

var_dump(file_get_contents($this->importFile));
var_dump($response->getBody()->getContents());
die;

顺便说一句,我在命令 ( bin/console blah:custom-command) 中的 Symfony (3.4) 应用程序的上下文中调用它。上面的代码片段是我的一个服务类的一部分。

这会在我的终端中生成一个新创建但为空的文件和以下输出:

string(0) ""
string(2065) "{"id":"123", … }"
# the latter one is actually a large JSON string, I just shortened it here

有人知道我做错了什么吗?这实际上不是火箭科学。我现在越是困惑,我下载的目标文件已经创建,但它的内容不会被写入......</p>

Guzzle 是否缺少某种配置或类似的配置?

标签: phpdownloadguzzleguzzle6

解决方案



推荐阅读