PHP实现m3u8并发下载
2021/8/2 1:35:43
本文主要是介绍PHP实现m3u8并发下载,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
直接上代码
<?php //php下载m3u8文件 $url = $argv['1']; if(!file_exists('./tmp/')) { if(!mkdir('./tmp/')) { die('请手动在当前目录创建tmp目录'); } } $indexPage = file_get_contents($url); preg_match_all('/.*\.ts/', $indexPage, $matches); if(empty($matches)) { die('m3u8 文件格式错误'); } go(function() use($matches) { $chan = new chan(100); //最大并发数 foreach($matches['0'] as $key => $value) { if(file_exists('./tmp/'.$key.'.ts')) { continue; } $chan->push('xx'); go(function() use($key, $value, $chan) { echo "\nAdd task:".$key; while(1) { $rs = co_curl($value); if(strlen($rs) > 0) { file_put_contents('./tmp/'.$key.'.ts', $rs); break; } } echo "\nTask ok:".$key; $chan->pop(); }); } //确保所有下载已经完成 for($i = 0; $i < 100; $i++) { $chan->push('over'); } //合并文件 foreach ($matches['0'] as $key => $value) { file_put_contents('out.mp4', file_get_contents('./tmp/'.$key.'.ts'), FILE_APPEND); unlink('./tmp/'.$key.'.ts'); } echo "\n 下载完成,转换成功 (out.mp4)"; }); function co_curl($url, $cookies = '', $data = array(), $userHeaders = array(), $retJson = 0) { while(1) { $urlInfo = parse_url($url); $domain = $urlInfo['host']; if($urlInfo['scheme'] == 'https') { $port = 443; $ssl = true; } else { $port = isset($urlInfo['port']) ? $urlInfo['port'] : 80; $ssl = false; } $filename = $urlInfo['path']; $filename .= isset($urlInfo['query']) ? '?' . $urlInfo['query'] : ''; $cli = new Swoole\Coroutine\Http\Client($domain, $port, $ssl); $headers = [ 'Host' => $domain, "User-Agent" => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36', 'Accept' => 'text/html,application/xhtml+xml,application/xml', 'Accept-Encoding' => 'gzip', ]; if ($userHeaders) { $headers = array_merge($headers, $userHeaders); $headers = $userHeaders; } if ($cookies) { $headers['Cookie'] = $cookies; } $cli->setHeaders($headers); $cli->set(['timeout' => 60]); if ($data) { if($data == 'post') { $data = ''; } $cli->post($filename, $data); } else { $cli->get($filename); } $body = $cli->body; $cli->close(); if($cli->statusCode < 1 || ($retJson && empty(json_decode($body, true)))) { // echo "\n status code:" . $cli->statusCode; // echo "\n body: ".$body; // echo "\n retry..."; } else { return $body; } } }
使用方法
php index.php https://doubanzyv1.tyswmp.com/2018/07/30/LSn7hSBfY0LxpKX2/playlist.m3u8
输出文件路径
当前目录的out.mp4
这篇关于PHP实现m3u8并发下载的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-19php8的协程和hyperf的协程有什么区别?-icode9专业技术文章分享
- 2024-12-19php8 的fiber是什么?-icode9专业技术文章分享
- 2024-12-05怎么在php8,1 里面开启 debug?-icode9专业技术文章分享
- 2024-12-05怎么在php8,1 里面开启 debug?-icode9专业技术文章分享
- 2024-11-29使用PHP 将ETH账户的资产汇集到一个账户
- 2024-11-23怎么实现安卓+php 热更新方案?-icode9专业技术文章分享
- 2024-11-22PHP 中怎么实现判断多个值是否为空、null 或者为 false?-icode9专业技术文章分享
- 2024-11-11开源 PHP 商城项目 CRMEB 二次开发和部署教程
- 2024-11-09怎么使用php在kaufland平台刊登商品?-icode9专业技术文章分享
- 2024-11-05PHP的抽象类和接口是什么,有什么区别-icode9专业技术文章分享