安装 guzzlehttp/guzzle、symfony/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');