guzzlehttp/guzzle配合symfony/console命令行实现文件下载进度条

guzzlehttp/guzzle 配合 symfony/console 命令行中实现文件下载进度条

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');

相关链接

  • https://github.com/symfony/console
  • https://github.com/guzzle/guzzle
  • https://github.com/guanguans/music-php

原文链接

  • https://github.com/guanguans/guanguans.github.io

以上是 guzzlehttp/guzzle配合symfony/console命令行实现文件下载进度条 的全部内容, 来源链接: utcz.com/a/45561.html

回到顶部