php - 在 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 是否缺少某种配置或类似的配置?
解决方案
推荐阅读
- reactjs - 如何从无限重新渲染中离开?
- python - 根据分组数据框中列的前两个值的差异获取子数据框
- javascript - 如何单击按钮切换滑块的图像
- python - Python3 __init__.py 如何存储包信息?
- java - Android Java Play gif 只播放一次
- c++builder - 更改线序时,网格内 FDQuery 的 Refresh() 函数似乎不起作用
- excel - Excel VBA 宏 - 类范围的复制方法失败
- c# - 是否可以在不加载 EF6 的情况下修改实体上的导航集合?
- javascript - Quill.js 和段落
- ios - 使用 foreach 的标签创建多个图像视图