首页 > 解决方案 > 用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 版本的选项。

标签: phpguzzlephp-5.4

解决方案


您可以使用 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


推荐阅读