php - 用guzzle下载pdf
问题描述
我想用 guzzle 下载一个 pdf 文件。这可能吗?
我试过这段代码:
$response = $this->client->post(self::API_BASE_URL.self::API_LABEL_URL,
[
'future' => true,
'json' => [$this->json],
'headers' => ['Content-Type' => 'application/json', 'Accept' => 'application/pdf'],
'query' => [
'return-type' => 'pdf',
'x-api-key' => $this->apiKey
],
]);
我得到
[body] => GuzzleHttp\Stream\Stream Object(
[stream:GuzzleHttp\Stream\Stream:private] => Resource id #120
[size:GuzzleHttp\Stream\Stream:private] => 649
[seekable:GuzzleHttp\Stream\Stream:private] => 1
[readable:GuzzleHttp\Stream\Stream:private] => 1
[writable:GuzzleHttp\Stream\Stream:private] => 1
[uri:GuzzleHttp\Stream\Stream:private] => php://temp
[customMetadata:GuzzleHttp\Stream\Stream:private] => Array
但我不知道如何处理此资源 ID 以保存 pdf 文件。我使用 guzzle 5.3 和 PHP 5.4,没有更新 php 版本的选项。
解决方案
您可以使用 Guzzle sink选项下载文件 - http://docs.guzzlephp.org/en/stable/request-options.html#sink
$pdfFilePath = __DIR__ . '/resource/file.pdf'; // specify your path
$pdfFileResource = fopen($pdfFilePath, 'w+');
$this->client->post(
self::API_BASE_URL . self::API_LABEL_URL,
[
'future' => true,
'json' => [$this->json],
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/pdf'
],
'query' => [
'return-type' => 'pdf',
'x-api-key' => $this->apiKey
],
'sink' => $pdfFileResource
]
);
更多示例 - https://github.com/andriichuk/php-curl-cookbook#download-file
推荐阅读
- java - Android Studio 项目结构问题
- isabelle - Isabelle 代码生成,用于终止可能非终止函数的使用
- reactjs - SassError:找不到或无法读取要导入的文件:~@henris/utils
- hybris - 自定义面包屑
- servicenow - 现在无法获得服务中的总结果数
- reactjs - 如何在 React 中更改 svg 图标颜色?
- sapui5 - Eclipse 中的 SAP UI5 插件
- apple-m1 - 错误:即使在 Intel 架构上运行,也仅支持 Mac 64 位
- javascript - 我可以在 Google Apps 脚本库中使用 Class 对象吗?
- typescript - 打字稿 - 键入 KeyValuePair
不可分配给类型 KeyValuePair