guzzlehttp/guzzle 配合 symfony/console 命令列中實現檔案下載進度條

guanguans發表於2020-09-24

usage

安裝 guzzlehttp/guzzlesymfony/console

$ composer require guzzlehttp/guzzle
$ composer require symfony/console

程式碼示例

#!/usr/bin/env php
<?php

require __DIR__.'/vendor/autoload.php';

use GuzzleHttp\Client;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Output\ConsoleOutput;

$fileDownloadUrl = 'http://ws.stream.qqmusic.qq.com/M8000004q1zZ43bMMs.mp3?guid=749170908&vkey=B5BC4501101100E9E4A10A83EEF1DD8FD27E6BD4F6C47C05964182534A9408A822A4E043B158E6D1E16B60336C746F048D5E239713A3A803&uin=0&fromtag=66%';
$saveFilePath    = '/Users/yaozm/Downloads/熱河 - 不只是南方.mp3';
$isDownloaded    = false;
$output          = new ConsoleOutput();
$progressBar     = null;

$client = new Client([
    'sink'     => $saveFilePath,
    'progress' => function ($totalDownload, $downloaded) use ($output, &$progressBar, &$isDownloaded){
        if ($totalDownload > 0 && $downloaded > 0 && null === $progressBar) {
            $progressBar = new ProgressBar($output, $totalDownload);
            $progressBar->setFormat('very_verbose');
            $progressBar->start();
        }
        if (!$isDownloaded && $progressBar && $totalDownload === $downloaded) {
            $progressBar->finish();
            $output->writeln(PHP_EOL);

            return $isDownloaded = true;
        }
        if ($progressBar) {
            $progressBar->setProgress($downloaded);
        }
    },
]);

$client->get($fileDownloadUrl);
$output->writeln('Download completed');

相關連結

原文連結

本作品採用《CC 協議》,轉載必須註明作者和本文連結
No practice, no gain in one's wit. 我的 Gitub

相關文章