大量下载pdf

时间:2019-05-03 09:10:01

标签: php guzzle php-5.4

我想下载一个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版本。

1 个答案:

答案 0 :(得分:0)

您可以使用Guzzle的接收器选项下载文件-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/curl-examples#download-file