PHP 接口使用 StreamSaver.js 从 B 站下载视频
以下是一个使用 PHP 编写的接口,用于从 B 站下载视频并保存到本地:
<?php
function downloadBilibiliVideo($url, $savePath) {
$streamUrl = getStreamUrl($url);
if (!$streamUrl) {
return false;
}
$file = fopen($savePath, 'w');
$ch = curl_init($streamUrl);
curl_setopt($ch, CURLOPT_FILE, $file);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($file);
return true;
}
function getStreamUrl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.jimmywarting.github.io/streamSaver.js/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'url=' . $url);
$response = curl_exec($ch);
curl_close($ch);
$responseJson = json_decode($response, true);
if (isset($responseJson['success']) && $responseJson['success'] === true) {
return $responseJson['url'];
}
return false;
}
// Example usage
$url = 'https://www.bilibili.com/video/BV1Kb411W75N';
$savePath = 'path/to/save/video.mp4';
if (downloadBilibiliVideo($url, $savePath)) {
echo 'Video downloaded successfully!';
} else {
echo 'Failed to download video.';
}
请确保你的服务器支持 cURL 扩展,并将path/to/save/video.mp4替换为你想保存视频的路径。还要注意,这个接口使用了 StreamSaver.js 来实现流式下载,因此你需要在服务器上部署 StreamSaver.js 库。
原文地址: https://www.cveoy.top/t/topic/o61u 著作权归作者所有。请勿转载和采集!