API仅供学习交流使用，禁止用于商业用途、违法用途等，否则后果自负！PHP版：（画质有点问题自己修复，Cookie改成自己的）<?php // 开启错误报告 error_reporting(E_ALL); ini_set('display_errors', 1); // 获取用户传入的 B 站视频链接 $videoUrl = $_GET['url'] ?? ''; // 解析视频链接，获取视频的 BV 号 preg_match('/(BV[a-zA-Z0-9]+)/', $videoUrl, $matches); if (empty($matches)) { header('Content-Type: application/json'); echo json_encode([ 'code' => 400, 'message' => '未找到有效的 BV 号', 'tips' => '美言AI' ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); exit; } $bvid = $matches[1]; // 构建获取视频信息的 API URL $apiUrl = "https://api.bilibili.com/x/web-interface/view?bvid={$bvid}"; // 记录日志函数 function logMessage($message) { $logFile = 'bilibili_api.log'; $logMessage = date('Y-m-d H:i:s') . " - " . $message . PHP_EOL; file_put_contents($logFile, $logMessage, FILE_APPEND); } // 使用 cURL 发送请求并设置头信息 $ch = curl_init($apiUrl); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Referer: https://www.bilibili.com/' ] ]); $response = curl_exec($ch); if ($response === false) { logMessage("获取视频信息 API 请求失败: " . curl_error($ch)); header('Content-Type: application/json'); echo json_encode([ 'code' => 500, 'message' => '获取视频信息 API 请求失败', 'tips' => '美言AI' ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); curl_close($ch); exit; } curl_close($ch); // 解析 JSON 响应 $responseData = json_decode($response, true); if ($responseData['code'] === 0) { $videoInfo = $responseData['data']; $title = $videoInfo['title']; $author = $videoInfo['owner']['name']; $cover = $videoInfo['pic']; $cid = $videoInfo['cid']; // 构建获取视频播放地址的 API URL $playUrlApi = "https://api.bilibili.com/x/player/playurl?bvid={$bvid}&cid={$cid}&fnval=16&platform=html5&qn=80"; // 在这里加入你的 Cookie $cookie = ""; // 控制请求间隔，避免触发限制 usleep(500000); // 暂停 0.5 秒 $ch = curl_init($playUrlApi); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Referer: https://www.bilibili.com/', "Cookie: $cookie", 'Accept: */*', 'Accept-Language: zh-CN,zh;q=0.9', 'Connection: keep-alive', 'TE: Trailers' ] ]); $playUrlResponse = curl_exec($ch); if ($playUrlResponse === false) { logMessage("获取视频播放地址 API 请求失败: " . curl_error($ch)); header('Content-Type: application/json'); echo json_encode([ 'code' => 500, 'message' => '获取视频播放地址 API 请求失败', 'tips' => '美言AI' ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); curl_close($ch); exit; } curl_close($ch); $playUrlData = json_decode($playUrlResponse, true); $playUrl = ''; if ($playUrlData['code'] === 0) { // 优先检查dash格式（支持1080p+高清） if (!empty($playUrlData['data']['dash']['video'])) { // 按码率降序排序获取最高清版本 usort($playUrlData['data']['dash']['video'], function($a, $b) { return $b['bandwidth'] - $a['bandwidth']; }); // 获取第一个（最高清）视频流 $videoStream = $playUrlData['data']['dash']['video'][0]; $baseVideoUrl = $videoStream['baseUrl']; // 获取对应的音频流 $audioStream = $playUrlData['data']['dash']['audio'][0] ?? null; $baseAudioUrl = $audioStream['baseUrl'] ?? ''; // 合并视频和音频地址 $playUrl = $baseVideoUrl; if (!empty($baseAudioUrl)) { $playUrl .= '|' . $baseAudioUrl; } // 修正参数：使用html5平台参数，去除不必要的mid参数 $playUrl = preg_replace('/mid=\d+/', 'mid=0', $playUrl); $playUrl = str_replace('platform=pc', 'platform=html5', $playUrl); } // 回退到durl方案（如果dash不可用） elseif (!empty($playUrlData['data']['durl'][0]['url'])) { $durl = $playUrlData['data']['durl'][0]['url']; $playUrl = str_replace( ['platform=pc', 'mid='.urlencode($videoInfo['owner']['mid'])], ['platform=html5', 'mid=0'], $durl ); } } else { logMessage("获取视频播放地址失败，错误信息: " . json_encode($playUrlData)); } // 返回解析结果 header('Content-Type: application/json'); echo json_encode([ 'code' => 200, 'title' => $title, 'author' => $author, 'cover' => $cover, 'play_url' => $playUrl, 'tips' => '美言AI' ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); } else { logMessage("未找到视频信息，错误信息: " . json_encode($responseData)); header('Content-Type: application/json'); echo json_encode([ 'code' => 404, 'message' => '未找到视频信息', 'tips' => '美言AI' ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); } ?>高画质版：（但是视频加载0秒未修复）<?php // 开启错误报告 error_reporting(E_ALL); ini_set('display_errors', 1); // 获取用户传入的 B 站视频链接 $videoUrl = $_GET['url'] ?? ''; // 解析视频链接，获取视频的 BV 号 preg_match('/(BV[a-zA-Z0-9]+)/', $videoUrl, $matches); if (empty($matches)) { header('Content-Type: application/json'); echo json_encode([ 'code' => 400, 'message' => '未找到有效的 BV 号', 'tips' => '美言AI' ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); exit; } $bvid = $matches[1]; // 构建获取视频信息的 API URL $apiUrl = "https://api.bilibili.com/x/web-interface/view?bvid={$bvid}"; // 记录日志函数 function logMessage($message) { $logFile = 'bilibili_api.log'; $logMessage = date('Y-m-d H:i:s') . " - " . $message . PHP_EOL; file_put_contents($logFile, $logMessage, FILE_APPEND); } // 使用 cURL 发送请求并设置头信息 $ch = curl_init($apiUrl); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Referer: https://www.bilibili.com/' ] ]); $response = curl_exec($ch); if ($response === false) { logMessage("获取视频信息 API 请求失败: " . curl_error($ch)); header('Content-Type: application/json'); echo json_encode([ 'code' => 500, 'message' => '获取视频信息 API 请求失败', 'tips' => '美言AI' ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); curl_close($ch); exit; } curl_close($ch); // 解析 JSON 响应 $responseData = json_decode($response, true); if ($responseData['code'] === 0) { $videoInfo = $responseData['data']; $title = $videoInfo['title']; $author = $videoInfo['owner']['name']; $cover = $videoInfo['pic']; $cid = $videoInfo['cid']; // 构建获取视频播放地址的 API URL，使用fnval=1 $playUrlApi = "https://api.bilibili.com/x/player/playurl?bvid={$bvid}&cid={$cid}&fnval=1"; // 在这里加入你的 Cookie，需要替换为有效的 Cookie $cookie = ""; // 控制请求间隔，避免触发限制 usleep(500000); // 暂停 0.5 秒 $ch = curl_init($playUrlApi); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Referer: https://www.bilibili.com/', "Cookie: $cookie", 'Accept: */*', 'Accept-Language: zh-CN,zh;q=0.9', 'Connection: keep-alive', 'TE: Trailers' ] ]); $playUrlResponse = curl_exec($ch); if ($playUrlResponse === false) { logMessage("获取视频播放地址 API 请求失败: " . curl_error($ch)); header('Content-Type: application/json'); echo json_encode([ 'code' => 500, 'message' => '获取视频播放地址 API 请求失败', 'tips' => '美言AI' ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); curl_close($ch); exit; } curl_close($ch); $playUrlData = json_decode($playUrlResponse, true); $playUrl = ''; if ($playUrlData['code'] === 0) { // 优先检查durl，若不存在则检查dash if (!empty($playUrlData['data']['durl'][0]['url'])) { $playUrl = $playUrlData['data']['durl'][0]['url']; // 添加必要的请求头 $headers = [ 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Referer: https://www.bilibili.com/', "Cookie: $cookie", 'Accept: */*', 'Accept-Language: zh-CN,zh;q=0.9', 'Connection: keep-alive', 'TE: Trailers' ]; $context = stream_context_create([ 'http' => [ 'method' => 'HEAD', 'header' => implode("\r\n", $headers) ] ]); $headers = @get_headers($playUrl, 1, $context); if ($headers && isset($headers['Content-Type']) && strpos($headers['Content-Type'], 'video')!== false) { // 确保是视频类型 } else { $playUrl = ''; } } elseif (!empty($playUrlData['data']['dash']['video'][0]['baseUrl'])) { $playUrl = $playUrlData['data']['dash']['video'][0]['baseUrl']; // 添加必要的请求头 $headers = [ 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Referer: https://www.bilibili.com/', "Cookie: $cookie", 'Accept: */*', 'Accept-Language: zh-CN,zh;q=0.9', 'Connection: keep-alive', 'TE: Trailers' ]; $context = stream_context_create([ 'http' => [ 'method' => 'HEAD', 'header' => implode("\r\n", $headers) ] ]); $headers = @get_headers($playUrl, 1, $context); if ($headers && isset($headers['Content-Type']) && strpos($headers['Content-Type'], 'video')!== false) { // 确保是视频类型 } else { $playUrl = ''; } } } else { logMessage("获取视频播放地址失败，错误信息: " . json_encode($playUrlData)); } // 返回解析结果 header('Content-Type: application/json'); echo json_encode([ 'code' => 200, 'title' => $title, 'author' => $author, 'cover' => $cover, 'play_url' => $playUrl, 'tips' => '美言AI' ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); } else { logMessage("未找到视频信息，错误信息: " . json_encode($responseData)); header('Content-Type: application/json'); echo json_encode([ 'code' => 404, 'message' => '未找到视频信息', 'tips' => '美言AI' ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); } ?>
API仅供学习交流使用，禁止用于商业用途、违法用途等，否则后果自负！请求链接：http://xxx.com/1.php?url=https://mp.weixin.qq.com/s/xxxPHP版：<?php // 获取用户传入的文章URL $articleUrl = $_GET['url'] ?? ''; if (empty($articleUrl)) { header('Content-Type: application/json'); echo json_encode([ 'code' => 400, 'msg' => '缺少文章URL参数' ], JSON_UNESCAPED_UNICODE); exit; } // 配置cURL请求（终极版模拟） $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $articleUrl, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_USERAGENT => 'Mozilla/5.0 (Linux; Android 13; MI 11 Build/TKQ1.220829.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/126.0.6478.188 Mobile Safari/537.36 MicroMessenger/8.0.50.2401(0x2800325F) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64', CURLOPT_REFERER => 'https://mp.weixin.qq.com/', CURLOPT_ENCODING => 'gzip, deflate, br', CURLOPT_HTTPHEADER => [ 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', 'Accept-Language: zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7', 'Cache-Control: max-age=0', 'Connection: keep-alive', 'Sec-Fetch-Dest: document', 'Sec-Fetch-Mode: navigate', 'Sec-Fetch-Site: same-origin', 'Sec-Fetch-User: ?1', 'Upgrade-Insecure-Requests: 1', 'X-Requested-With: com.tencent.mm', 'Cookie: ' . http_build_query([ 'appmsg_token' => generate_token(), 'mm_lang' => 'zh_CN', 'reward_sn' => '' ]) ] ]); // 获取文章HTML内容 $html = curl_exec($ch); curl_close($ch); if (!$html) { header('Content-Type: application/json'); echo json_encode([ 'code' => 500, 'msg' => '获取文章内容失败' ], JSON_UNESCAPED_UNICODE); exit; } // 解析HTML内容 $dom = new DOMDocument(); libxml_use_internal_errors(true); @$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); libxml_clear_errors(); /****************** 提取文章标题******************/ $title = '未知标题'; $metaNodes = $dom->getElementsByTagName('meta'); foreach ($metaNodes as $node) { $property = $node->getAttribute('property'); if ($property === 'og:title') { $title = htmlspecialchars_decode(trim($node->getAttribute('content'))); break; } } /****************** 图片提取部分******************/ $contentDiv = $dom->getElementById('js_content') ?? $dom->getElementsByTagName('div')->item(0); $imageUrls = []; if ($contentDiv) { $images = $contentDiv->getElementsByTagName('img'); foreach ($images as $img) { $src = $img->getAttribute('data-src') ?: $img->getAttribute('src'); if ($src) { $fullUrl = parse_url($src, PHP_URL_SCHEME) ? $src : 'https://' . ltrim($src, '/'); $fullUrl .= (strpos($fullUrl, '?') === false ? '?' : '&') . 'wxfrom=5&wx_lazy=1'; $imageUrls[] = $fullUrl; } } } // 返回结果 header('Content-Type: application/json'); echo json_encode([ 'code' => empty($imageUrls) ? 201 : 200, 'title' => $title, 'image_urls' => $imageUrls, 'tips' => '解析失败多试几次，Meiyan美言AI' ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); // 生成动态token（模拟微信客户端） function generate_token($length = 32) { return substr(str_shuffle('0123456789abcdef'), 0, $length); }适配图集和公众号昵称版：<?php // 获取用户传入的文章URL $articleUrl = $_GET['url']?? ''; if (empty($articleUrl)) { header('Content-Type: application/json'); echo json_encode([ 'code' => 400, 'msg' => '缺少文章URL参数' ], JSON_UNESCAPED_UNICODE); exit; } // 配置cURL请求 $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $articleUrl, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_SSL_VERIFYPEER => false, // 尝试更换User-Agent CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36', CURLOPT_REFERER => 'https://mp.weixin.qq.com/', CURLOPT_ENCODING => 'gzip, deflate, br', CURLOPT_HTTPHEADER => [ 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', 'Accept-Language: zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7', 'Cache-Control: max-age=0', 'Connection: keep-alive', 'Sec-Fetch-Dest: document', 'Sec-Fetch-Mode: navigate', 'Sec-Fetch-Site: same-origin', 'Sec-Fetch-User:?1', 'Upgrade-Insecure-Requests: 1', 'X-Requested-With: com.tencent.mm', 'Cookie: '. http_build_query([ 'appmsg_token' => generate_token(), 'mm_lang' => 'zh_CN', 'reward_sn' => '' ]) ] ]); // 获取文章HTML内容 $html = curl_exec($ch); if ($html === false) { // 获取详细的cURL错误信息 $error = curl_error($ch); header('Content-Type: application/json'); echo json_encode([ 'code' => 500, 'msg' => '获取文章内容失败: '. $error ], JSON_UNESCAPED_UNICODE); exit; } curl_close($ch); // 解析HTML内容 $dom = new DOMDocument(); libxml_use_internal_errors(true); @$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); libxml_clear_errors(); /****************** 提取文章标题******************/ $title = '未知标题'; $metaNodes = $dom->getElementsByTagName('meta'); foreach ($metaNodes as $node) { $property = $node->getAttribute('property'); if ($property === 'og:title') { $title = htmlspecialchars_decode(trim($node->getAttribute('content'))); break; } } /****************** 提取公众号名称 ******************/ $username = '未知公众号'; $divs = $dom->getElementsByTagName('div'); foreach ($divs as $div) { if ($div->hasAttribute('class') && strpos($div->getAttribute('class'), 'wx_follow_nickname')!== false) { $username = htmlspecialchars_decode(trim($div->textContent)); break; } } /****************** 图片提取部分******************/ $imageUrls = []; $allImages = $dom->getElementsByTagName('img'); foreach ($allImages as $img) { $src = $img->getAttribute('data-src')?: $img->getAttribute('src'); if (empty($src)) continue; // 处理相对路径 if (substr($src, 0, 2) === '//') { $fullUrl = 'https:'. $src; } elseif ($src[0] === '/') { $fullUrl = 'https://'. parse_url($articleUrl, PHP_URL_HOST). $src; } else { $fullUrl = $src; } // 过滤非微信图片 $host = parse_url($fullUrl, PHP_URL_HOST); if (strpos($host, 'qpic.cn') === false) continue; // 添加必要参数 $separator = strpos($fullUrl, '?') === false? '?' : '&'; $fullUrl.= $separator. 'wxfrom=5&wx_lazy=1'; $imageUrls[] = $fullUrl; } // 提取纯图集中的图片链接 if (preg_match_all('/cdn_url:\s*\'([^\']+)\'/', $html, $matches)) { foreach ($matches[1] as $cdnUrl) { // 添加必要参数 $separator = strpos($cdnUrl, '?') === false? '?' : '&'; $fullUrl = $cdnUrl. $separator. 'wxfrom=5&wx_lazy=1'; $imageUrls[] = $fullUrl; } } // 返回结果 header('Content-Type: application/json'); echo json_encode([ 'code' => empty($imageUrls)? 201 : 200, 'title' => $title, 'username' => $username, 'image_urls' => array_values(array_unique($imageUrls)), // 去重并确保索引连续 'tips' => '解析失败多试几次，Meiyan美言AI' ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); // 生成动态token（模拟微信客户端） function generate_token($length = 32) { return substr(str_shuffle('0123456789abcdef'), 0, $length); }
下面以抖音为例，原创提供的代码不完整，修复了一下。API仅供学习交流使用，禁止用于商业用途、违法用途等，否则后果自负！因为工作需要，研究了一下抖音的视频接口，都需要 cookie 、 msToken 、 a_bogus ....这些参数才能调用获取解析，而且 a_bogus 算法且复杂， cookie 也要时长更新，而我这个能跳过这些参数，直接能解析视频信息出来，无需 cookie 、 a_bogus ，且解析的视频一直都不会失效。解析前：解析后：实现原理当我们请求手机端的抖音链接的时候，在 F12 获取源代码能得到一些视频信息 json 数据，所以只需要正则取到源代码下面的 json 数据，请求头只需添加 User-Agent 、 Referer 即可，无需 cookie 。模拟请求，得到了需要的数据，再使用正则取出转成json数据再取出值即可。注意事项原贴：抖音视频链接 重定向错误分析 https://www.douyin.com/aweme/v1/play/?video_id=v0200fg10000cqd77sfog65gatpq9nm0 该链接是抖音无水印播放接口，且每次访问都会跳转到新的地址，按道理视频一直都不会失效， video_id 参数在页面能搜索到。贴上脚本PHP版：<?php $msg = urldecode($_REQUEST['msg']); //获取视频链接 if (is_numeric($msg)) { $video_id = $msg; } else { preg_match('/https?:\/\/[^\s]+/', $msg, $video_url); $video_url = $video_url[0]; $redirected_url = get_redirected_url($video_url); preg_match('/(\d+)/', $redirected_url, $matches); $video_id = $matches[1]; // echo $video_id; } function get_redirected_url($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_exec($ch); $redirected_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); curl_close($ch); return $redirected_url; } $headers = [ 'User-Agent: Mozilla/5.0 (Linux; Android 8.0.0; SM-G955U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36', 'Referer: https://www.douyin.com/?is_from_mobile_home=1&recommend=1' ]; $url = "https://www.iesdouyin.com/share/video/$video_id/"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); curl_close($ch); preg_match('/_ROUTER_DATA\s*=\s*(\{.*?\});/', $response, $matches); $data = $matches[1]; // 解析 JSON 数据 $jsonData = json_decode($data, true); // 获取视频信息 $itemList = $jsonData['loaderData']['video_(id)/page']['videoInfoRes']['item_list'][0]; $nickname = $itemList['author']['nickname']; $title = $itemList['desc']; $awemeId = $itemList['aweme_id']; $video = $itemList['video']['play_addr']['uri']; $videoUrl = $video !== null ? (strpos($video, 'mp3') === false ? 'https://www.douyin.com/aweme/v1/play/?video_id=' . $video : $video) : null; $cover = $itemList['video']['cover']['url_list'][0]; $images = $itemList['images'] ?? null; $output = [ 'msg' =>empty($nickname)?'解析失败！':'解析成功！', 'name' => $nickname, 'title' => $title, // 'aweme_id' => $awemeId, 'video' => $videoUrl, 'cover' => $cover, 'images' => array_map(function($image) { return $image['url_list'][0]; }, is_array($images) ? $images : []), 'type' =>empty($images)?'视频':'图集', 'tips' => '解析失败多试几次，Meiyan美言AI' ]; header('Content-Type: application/json'); echo json_encode($output,JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); ?>Python版：#Meiyan美言AI import requests import re import json headers ={ 'user-agent':'Mozilla/5.0 (Linux; Android 8.0.0; SM-G955U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36', 'referer':'https://www.douyin.com/?is_from_mobile_home=1&recommend=1' } url ='https://www.iesdouyin.com/share/video/7358413207083486505/' res =requests.get(url,headers=headers).text data =re.findall(r'_ROUTER_DATA\s*=\s*(\{.*?\});', res)[0] json_data =json.loads(data) # print(data) item_list =json_data['loaderData']['video_(id)/page']['videoInfoRes']['item_list'][0] nickname =item_list['author']['nickname'] title =item_list['desc'] aweme_id =item_list['aweme_id'] video =item_list['video']['play_addr']['uri'] video = 'https://www.douyin.com/aweme/v1/play/?video_id=' + video if 'mp3' not in video else video cover =item_list['video']['cover']['url_list'][0] img =item_list['images'] print(title) print(aweme_id) print(video) print(cover) for image in img: images = image['url_list'][0] print(images) #Meiyan美言AI修复版本上面提供的代码和作者提供的演示不一样，于是增加了一些。在 video 下增加 play_video 字段：通过 get_final_video_url() 函数获取视频的真实播放地址，如果获取失败则返回 null在 title 下新增 aweme_id 字段：从原始URL或重定向后的URL中提取数字ID（如 https://www.douyin.com/video/XXX 提取 XXX ）添加 header('Content-Type: application/json; charset=utf-8') 确保 UTF-8 编码，所有字符串处理都确保 UTF-8 兼容增加更多空值检查（?? 运算符）更完善的正则表达式匹配5.extract_aweme_id() - 专门用于从URL提取数字IDget_final_video_url() - 专门用于获取最终播放地址修改后的php版代码：<?php header('Content-Type: application/json; charset=utf-8'); $msg = urldecode($_REQUEST['msg']); // 获取视频链接 // 获取aweme_id（从URL提取最终的数字ID） function extract_aweme_id($url) { $redirected = get_redirected_url($url); preg_match('/\/(\d+)(?:\/|\?|$)/', $redirected, $matches); return $matches[1] ?? null; } if (is_numeric($msg)) { $video_id = $msg; $aweme_id = $msg; // 如果直接传入数字，则认为是aweme_id } else { preg_match('/https?:\/\/[^\s]+/', $msg, $video_url); $video_url = $video_url[0]; // 获取aweme_id（从原始URL或重定向后的URL） $aweme_id = extract_aweme_id($video_url); $redirected_url = get_redirected_url($video_url); preg_match('/(\d+)/', $redirected_url, $matches); $video_id = $matches[1]; } function get_redirected_url($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_exec($ch); $redirected_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); curl_close($ch); return $redirected_url; } function get_final_video_url($video_url) { if (empty($video_url)) return null; $ch = curl_init($video_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // 不自动跳转 curl_setopt($ch, CURLOPT_HEADER, true); // 获取头信息 curl_setopt($ch, CURLOPT_NOBODY, true); // 只获取头信息 curl_exec($ch); $redirect_url = curl_getinfo($ch, CURLINFO_REDIRECT_URL); curl_close($ch); return $redirect_url ?: $video_url; } $headers = [ 'User-Agent: Mozilla/5.0 (Linux; Android 8.0.0; SM-G955U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36', 'Referer: https://www.douyin.com/?is_from_mobile_home=1&recommend=1' ]; $url = "https://www.iesdouyin.com/share/video/$video_id/"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); curl_close($ch); preg_match('/_ROUTER_DATA\s*=\s*(\{.*?\});/', $response, $matches); $data = $matches[1] ?? '{}'; // 解析 JSON 数据 $jsonData = json_decode($data, true); // 获取视频信息 $itemList = $jsonData['loaderData']['video_(id)/page']['videoInfoRes']['item_list'][0] ?? []; $nickname = $itemList['author']['nickname'] ?? ''; $title = $itemList['desc'] ?? ''; $video = $itemList['video']['play_addr']['uri'] ?? ''; // 修改点：在视频地址后添加 req_cdn_type 参数 $videoUrl = $video ? (strpos($video, 'mp3') === false ? 'https://www.douyin.com/aweme/v1/play/?video_id=' . $video . '&req_cdn_type=' : $video) : null; $cover = $itemList['video']['cover']['url_list'][0] ?? ''; $images = $itemList['images'] ?? null; // 获取真实播放地址 $play_video = null; if ($videoUrl) { $play_video = get_final_video_url($videoUrl); } $output = [ 'msg' => empty($nickname) ? '解析失败！' : '解析成功！', 'name' => $nickname, 'title' => $title, 'id' => $aweme_id, // 新增的aweme_id字段 'video' => $videoUrl, 'play_video' => $play_video, // 新增的真实播放地址 'cover' => $cover, 'images' => array_map(function($image) { return $image['url_list'][0] ?? ''; }, is_array($images) ? $images : []), 'type' => empty($images) ? '视频' : '图集', 'tips' => '解析失败多试几次，Meiyan美言AI' ]; echo json_encode($output, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); ?>在获取到的 play_video 地址后面添加 &req_cdn_type= 参数版：<?php header('Content-Type: application/json; charset=utf-8'); $msg = urldecode($_REQUEST['msg']); // 获取视频链接 // 获取aweme_id（从URL提取最终的数字ID） function extract_aweme_id($url) { $redirected = get_redirected_url($url); preg_match('/\/(\d+)(?:\/|\?|$)/', $redirected, $matches); return $matches[1] ?? null; } if (is_numeric($msg)) { $video_id = $msg; $aweme_id = $msg; // 如果直接传入数字，则认为是aweme_id } else { preg_match('/https?:\/\/[^\s]+/', $msg, $video_url); $video_url = $video_url[0]; // 获取aweme_id（从原始URL或重定向后的URL） $aweme_id = extract_aweme_id($video_url); $redirected_url = get_redirected_url($video_url); preg_match('/(\d+)/', $redirected_url, $matches); $video_id = $matches[1]; } function get_redirected_url($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_exec($ch); $redirected_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); curl_close($ch); return $redirected_url; } function get_final_video_url($video_url) { if (empty($video_url)) return null; // 初始化cURL $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $video_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // 不自动跳转 curl_setopt($ch, CURLOPT_HEADER, true); // 获取头信息 curl_setopt($ch, CURLOPT_NOBODY, true); // 只获取头信息 curl_exec($ch); // 获取重定向URL $redirect_url = curl_getinfo($ch, CURLINFO_REDIRECT_URL); curl_close($ch); // 如果没有重定向URL，返回原始URL $final_url = $redirect_url ?: $video_url; // 添加req_cdn_type参数 req_cdn_type=1 可以是空也可以是1/2/3 if (strpos($final_url, '?') === false) { $final_url .= '?req_cdn_type='; } else { $final_url .= '&req_cdn_type='; } return $final_url; } $headers = [ 'User-Agent: Mozilla/5.0 (Linux; Android 8.0.0; SM-G955U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36', 'Referer: https://www.douyin.com/?is_from_mobile_home=1&recommend=1' ]; $url = "https://www.iesdouyin.com/share/video/$video_id/"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); curl_close($ch); preg_match('/_ROUTER_DATA\s*=\s*(\{.*?\});/', $response, $matches); $data = $matches[1] ?? '{}'; // 解析 JSON 数据 $jsonData = json_decode($data, true); // 获取视频信息 $itemList = $jsonData['loaderData']['video_(id)/page']['videoInfoRes']['item_list'][0] ?? []; $nickname = $itemList['author']['nickname'] ?? ''; $title = $itemList['desc'] ?? ''; $video = $itemList['video']['play_addr']['uri'] ?? ''; $videoUrl = $video ? (strpos($video, 'mp3') === false ? 'https://www.douyin.com/aweme/v1/play/?video_id=' . $video : $video) : null; $cover = $itemList['video']['cover']['url_list'][0] ?? ''; $images = $itemList['images'] ?? null; // 获取真实播放地址（已添加req_cdn_type参数） $play_video = null; if ($videoUrl) { $play_video = get_final_video_url($videoUrl); } $output = [ 'msg' => empty($nickname) ? '解析失败！' : '解析成功！', 'name' => $nickname, 'title' => $title, 'id' => $aweme_id, // 新增的aweme_id字段 'video' => $videoUrl, 'play_video' => $play_video, // 新增的真实播放地址（已添加req_cdn_type参数） 'cover' => $cover, 'images' => array_map(function($image) { return $image['url_list'][0] ?? ''; }, is_array($images) ? $images : []), 'type' => empty($images) ? '视频' : '图集', 'tips' => '解析失败多试几次，Meiyan美言AI' ]; echo json_encode($output, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); ?>使用方法现在只支持解析 图集 or 视频 ，后续可能会添加 Live实况 解析。请求示例： 域名?msg=视频链接 (msg可在代码$_REQUEST中换成其他)请求方式：GET/POST返回格式：JSON例如：视频链接：https://v.douyin.com/irC9f9js请求地址：http://xxx.com/1.php?msg=https://v.douyin.com/irC9f9js返回结果：解析问题有时候会解析失败，是因为代码没有算法CookieURL重定向失效，平台经常更新域名规则，旧的重定向解析方式可能失效平台前端经常改版，_ROUTER_DATA可能不存在或结构变化反爬虫机制，平台对自动化请求有严格限制网络环境问题，服务器IP被限制视频权限限制，私密视频/作者设置限制最右解析方法，几乎类似。直接 F12 看分析返回内容，然后自己键值对取值即可PHP代码：<?php $msg =$_GET['msg']; $parsed_url = parse_url($msg); parse_str($parsed_url['query'], $query_params); $pid = (int)($query_params['pid'] ?? null); $url = 'https://share.xiaochuankeji.cn/planck/share/post/detail_h5'; $data = [ 'pid' => $pid, 'h_av' => '5.2.13.011' ]; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json' ]); $response = curl_exec($ch); $responseData = json_decode($response, true); // 提取数据 $title = $responseData['data']['post']['content']; $name = $responseData['data']['post']['member']['name']; $imgs = $responseData['data']['post']['imgs']; $id = $responseData['data']['post']['imgs'][0]['id']; $videos = isset($responseData['data']['post']['videos'][strval($id)]) ? $responseData['data']['post']['videos'][strval($id)]['url'] : ''; foreach ($imgs as $img) { $img['urls']['540_webp']['urls'][0] . "\n"; } header('Content-Type: application/json'); echo json_encode([ 'code' =>empty($id)?201:200, 'name' => $name, 'title' => $title, 'video' => $videos, 'imgs' => array_map(function ($img) { return $img['urls']['540_webp']['urls'][0]; }, $imgs), 'tips' => '解析失败多试几次，Meiyan美言AI' ],JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); ?>Python代码：import re import requests msg ='https://share.xiaochuankeji.cn/hybrid/share/post?pid=402085918' # msg输入你要解析的最右app分享地址 pid =re.findall('pid=(\d+)',msg)[0] json = {"pid": int(pid), "h_av": "5.2.13.011"} url = 'https://share.xiaochuankeji.cn/planck/share/post/detail_h5' req = requests.post(url, json=json).json() # 提取数据 title = req['data']['post']['content'] name = req['data']['post']['member']['name'] imgs = req['data']['post']['imgs'] id = req['data']['post']['imgs'][0]['id'] videos = req['data']['post']['videos'].get(str(id))['url'] print(name,title) print('视频：',videos) print('图集：') for i in imgs: img = i['urls']['540_webp']['urls'][0] print(img)
php版 使用本地txt链接视频库 实现随机美女视频API
原版代码<?php // 请求参数说明： // 参数名称 是否必填 备注内容 // json 是 json格式响应 // down 是 302重定向响应 // &id= 否 视频id编号 // 设置 CORS 头部，允许跨域访问（如果需要） header("Access-Control-Allow-Origin: *"); // 设置响应内容类型为 JSON header("Content-Type: application/json; charset=UTF-8"); // 视频库链接地址 $videoFilePath = "Beautyvideo/Beautyvideo.txt"; // 第三方API：用于获取视频链接 $thirdPartyApiUrl = "https://api.kxzjoker.cn/API/Beautyvideo/Beauty_video_url.php"; // 第三方解析API：用于解析视频链接 $thirdPartyParseApiUrl = "https://api.kxzjoker.cn/API/jiexi_video_2.php?url="; // 获取请求参数 $type = isset($_GET['type']) ? trim($_GET['type']) : null; $id = isset($_GET['id']) ? (int) $_GET['id'] : null; // 使用第三方API来获取视频链接 //Yes则使用第三方视频库,No则使用本地视频库 $useThirdPartyApi = 'Yes'; // 建议使用第三方视频库,第三方视频库每天都会更新几百条视频 // 校验 'type' 参数 if ($type === null) { echo json_encode(["msg" => "请提供 'type' 参数", "time" => date("Y-m-d H:i:s")], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit; } // 处理第三方 API 请求 if ($useThirdPartyApi == 'Yes') { // 如果有 id 参数，附加到 API 请求的 URL 中 $thirdPartyApiUrl = $id !== null ? $thirdPartyApiUrl . "?id=" . urlencode($id) : $thirdPartyApiUrl; // 获取第三方API的视频链接 $thirdPartyResponse = @file_get_contents($thirdPartyApiUrl); if ($thirdPartyResponse === FALSE) { echo json_encode(["code" => 401, "msg" => "获取第三方视频链接失败，请联系管理员进行维护", "time" => date("Y-m-d H:i:s")], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit; } $thirdPartyData = json_decode($thirdPartyResponse, true); if (isset($thirdPartyData['url'], $thirdPartyData['Video_platform'], $thirdPartyData['video_number'], $thirdPartyData['video_id'])) { $videoLink = $thirdPartyData['url']; $video_platform = $thirdPartyData['Video_platform']; $video_number = $thirdPartyData['video_number']; $video_id = $thirdPartyData['video_id']; // 解析视频链接 $requestUrl = $thirdPartyParseApiUrl . urlencode($videoLink); $response = @file_get_contents($requestUrl); if ($response === FALSE) { echo json_encode(["code" => 401, "msg" => "解析请求失败，请联系管理员进行维护", "time" => date("Y-m-d H:i:s")], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit; } $data = json_decode($response, true); if (isset($data['data']['download_url'], $data['data']['image_url'], $data['data']['video_title'])) { $download_url = $data['data']['download_url']; $image_url = $data['data']['image_url']; $video_title = $data['data']['video_title']; if ($type == 'json') { echo json_encode([ "code" => 200, "video_title" => $video_title, "download_url" => $download_url, "image_url" => $image_url, "Video_platform" => $video_platform, "video_number" => $video_number, "video_id" => $video_id, "tips" => "接口由Wechat:Hello-byte提供", "time" => date("Y-m-d H:i:s") ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } elseif ($type == 'down') { header("Location: " . $download_url, true, 302); exit; } else { echo json_encode(["msg" => "无效的 'type' 参数", "time" => date("Y-m-d H:i:s")], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } } else { echo json_encode(["code" => 403, "msg" => "视频链接解析失败", "video_id" => $video_id, "time" => date("Y-m-d H:i:s")], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } } else { echo json_encode(["code" => 402, "msg" => "第三方API返回数据格式不正确", "time" => date("Y-m-d H:i:s")], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } } else { // 使用本地文件 Beautyvideo.txt 作为视频库 $videoLinks = @file($videoFilePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); if (empty($videoLinks)) { echo json_encode(["code" => 402, "msg" => "视频库有效链接失效，请联系网站管理员邮箱进行维护!", "tips" => "接口由Wechat:Hello-byte提供", "time" => date("Y-m-d H:i:s")], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit; } // 选择视频链接 if ($id !== null && $id >= 1 && $id <= count($videoLinks)) { $videoLink = $videoLinks[$id - 1]; $video_id = $id; } else { $videoLink = $videoLinks[array_rand($videoLinks)]; $video_id = array_search($videoLink, $videoLinks) + 1; } // 请求解析 $requestUrl = $thirdPartyParseApiUrl . urlencode($videoLink); $response = @file_get_contents($requestUrl); if ($response === FALSE) { echo json_encode(["code" => 401, "msg" => "解析请求失败，请联系管理员进行维护!", "time" => date("Y-m-d H:i:s")], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit; } $data = json_decode($response, true); if (isset($data['data']['download_url'], $data['data']['image_url'], $data['data']['video_title'])) { $download_url = $data['data']['download_url']; $image_url = $data['data']['image_url']; $video_title = $data['data']['video_title']; $video_platform = strpos($videoLink, 'kuaishou.com') !== false ? '快手' : (strpos($videoLink, 'douyin.com') !== false ? '抖音' : '未知平台'); if ($type == 'json') { echo json_encode([ "code" => 200, "video_title" => $video_title, "download_url" => $download_url, "image_url" => $image_url, "Video_platform" => $video_platform, "video_number" => count($videoLinks), "video_id" => $video_id, "tips" => "接口由Wechat:Hello-byte提供", "time" => date("Y-m-d H:i:s") ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } elseif ($type == 'down') { header("Location: ". $download_url, true, 302); exit; } else { echo json_encode(["msg" => "无效的 'type' 参数", "time" => date("Y-m-d H:i:s")], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } } else { echo json_encode(["code" => 403, "msg" => "视频链接解析失败，请联系网站管理员邮箱进行维护!", "video_id" => $video_id, "time" => date("Y-m-d H:i:s")], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); // **仅在本地视频库中删除失效链接** // 删除失效链接的部分 if ($useThirdPartyApi == 'No') { $indexToDelete = $video_id - 1; if ($indexToDelete >= 0 && $indexToDelete < count($videoLinks)) { array_splice($videoLinks, $indexToDelete, 1); file_put_contents($videoFilePath, implode("\n", $videoLinks)); } } } } ?> 修改后的1主要移除了使用第三方API，直接使用本地文件：/Beautyvideo/Beautyvideo.txt 作为视频库（要确保 /Beautyvideo/Beautyvideo.txt 文件存在且包含有效的视频链接，每行一个链接。）而且在原版基础上在 json_encode 函数中添加了 JSON_PRETTY_PRINT 标志来美化JSON输出。<?php // 设置 CORS 头部，允许跨域访问（如果需要） header("Access-Control-Allow-Origin: *"); // 设置响应内容类型为 JSON header("Content-Type: application/json; charset=UTF-8"); // 视频库链接地址 $videoFilePath = "Beautyvideo/Beautyvideo.txt"; // 第三方API：用于获取视频链接 $thirdPartyApiUrl = "https://api.kxzjoker.cn/API/Beautyvideo/Beauty_video_url.php"; // 获取请求参数 $type = isset($_GET['type']) ? trim($_GET['type']) : null; $id = isset($_GET['id']) ? (int) $_GET['id'] : null; // 校验 'type' 参数 if ($type === null) { echo json_encode(["msg" => "请提供 'type' 参数", "time" => date("Y-m-d H:i:s")], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); exit; } // 使用本地文件 Beautyvideo.txt 作为视频库 $videoLinks = @file($videoFilePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); if (empty($videoLinks)) { echo json_encode(["code" => 402, "msg" => "视频库有效链接失效，请联系网站管理员邮箱进行维护!", "time" => date("Y-m-d H:i:s")], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); exit; } // 选择视频链接 if ($id !== null && $id >= 1 && $id <= count($videoLinks)) { $videoLink = $videoLinks[$id - 1]; $video_id = $id; } else { $videoLink = $videoLinks[array_rand($videoLinks)]; $video_id = array_search($videoLink, $videoLinks) + 1; } // 判断视频平台 $video_platform = strpos($videoLink, 'kuaishou.com') !== false ? '快手' : (strpos($videoLink, 'douyin.com') !== false ? '抖音' : '未知平台'); // 返回JSON格式响应 if ($type == 'json') { echo json_encode([ "code" => 200, "url" => $videoLink, "Video_platform" => $video_platform, "video_number" => count($videoLinks), "video_id" => $video_id, "tips" => "接口由Wechat:Hello-byte提供", "time" => date("Y-m-d H:i:s") ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); } elseif ($type == 'down') { header("Location: " . $videoLink, true, 302); exit; } else { echo json_encode(["msg" => "无效的 'type' 参数", "time" => date("Y-m-d H:i:s")], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); } ?>修改后的2主要设置了默认是：json方式访问，实现默认访问http://v.syylw.com/api/Beauty_video.php 时即以json类型 访问，在PHP脚本 中设置一个默认值，使得当请求中没有提供 type参数 时，自动使用 json 作为默认值。<?php // 设置 CORS 头部，允许跨域访问（如果需要） header("Access-Control-Allow-Origin: *"); // 设置响应内容类型为 JSON header("Content-Type: application/json; charset=UTF-8"); // 视频库链接地址 $videoFilePath = "Beautyvideo/Beautyvideo.txt"; // 获取请求参数 $type = isset($_GET['type']) ? trim($_GET['type']) : 'json'; // 设置默认值为 'json' $id = isset($_GET['id']) ? (int) $_GET['id'] : null; // 使用本地文件 Beautyvideo.txt 作为视频库 $videoLinks = @file($videoFilePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); if (empty($videoLinks)) { echo json_encode(["code" => 402, "msg" => "视频库有效链接失效，请联系网站管理员邮箱进行维护!", "time" => date("Y-m-d H:i:s")], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); exit; } // 选择视频链接 if ($id !== null && $id >= 1 && $id <= count($videoLinks)) { $videoLink = $videoLinks[$id - 1]; $video_id = $id; } else { $videoLink = $videoLinks[array_rand($videoLinks)]; $video_id = array_search($videoLink, $videoLinks) + 1; } // 判断视频平台 $video_platform = strpos($videoLink, 'kuaishou.com') !== false ? '快手' : (strpos($videoLink, 'douyin.com') !== false ? '抖音' : '未知平台'); // 返回JSON格式响应 if ($type == 'json') { echo json_encode([ "code" => 200, "url" => $videoLink, "Video_platform" => $video_platform, "video_number" => count($videoLinks), "video_id" => $video_id, "tips" => "接口由Wechat:Hello-byte提供", "time" => date("Y-m-d H:i:s") ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); } elseif ($type == 'down') { header("Location: " . $videoLink, true, 302); exit; } else { echo json_encode(["msg" => "无效的 'type' 参数", "time" => date("Y-m-d H:i:s")], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); } ?>在这个修改后的代码中，我将获取 type参数 的逻辑修改为：$type = isset($_GET['type']) ? trim($_GET['type']) : 'json'; // 设置默认值为 'json'这意味着如果请求中没有提供 type参数，$type 将自动被设置为'json'。这样，当用户访问 http://v.syylw.com/api/Beauty_video.php 时，如果没有指定 type参数，系统将默认以 json类型 进行响应。原版API【随机美女视频视频库】请求说明：请求地址：https://api.kxzjoker.cn/API/Beautyvideo/Beauty_video_url.php返回格式：JSON请求方式：GET/POST请求示例：https://api.kxzjoker.cn/API/Beautyvideo/Beauty_video_url.php返回示例：{ "code": 200, "url": "https://v.kuaishou.com/dmOrEd", "Video_platform": "快手", "video_number": 1933, "video_id": 59, "tips": "接口由看戏仔-API(http://api.kxzjoker.cn/)免费提供", "time": "2024-12-25 21:55:54" }请求参数：参数名称是否必填备注内容id否视频id编号返回参数：参数名称参数类型参数说明urlstring视频地址Video_platformstring视频平台video_numberstring当前接口视频数量video_idstring视频id编号访问返回：{ "code": 200, "url": "https://v.kuaishou.com/imxxeZ", "Video_platform": "快手", "video_number": 12208, "video_id": 12033, "tips": "接口由看戏仔-API(http://api.kxzjoker.cn/)免费提供", "time": "2025-01-14 15:22:09" }原版API【聚合短视频解析（线路2）】请求说明：请求地址：https://api.kxzjoker.cn/API/jiexi_video_2.php返回格式：JSON/MP4请求方式：GET/POST请求示例：https://api.kxzjoker.cn/API/jiexi_video_2.php?url=https://v.douyin.com/i2q93e3N/返回示例：{ "success": true, "data": { "video_title": "定格美好瞬间~#旅行#转场#甜妹", "video_url": "https://v9-default.365yg.com/ba4e13cee3720eaeaefac247d54e34c6/676bfea3/video/tos/cn/tos-cn-ve-15/ogsAHdnXeCAEOB7bp9GKABzApcOIEDQbgmweXD/?a=2011&br=1675&bt=1675&btag=80000e00008000&cd=0%7C0%7C0%7C0&ch=0&cr=0&cs=0&cv=1&dr=0&ds=4&dy_q=1735127175&dy_va_biz_cert=&feature_id=46a7bb47b4fd1280f3d3825bf2b29388&ft=k7Fz7VVywhiRF_80mo~pK7pswApoiT6ZvrK40zTmto0g3cI&l=202412251946156AD44F7BFBC7EE19A41E&mime_type=video_mp4&net=5&qs=0&rc=NDZpN2Q2ZjZkZDczZDc2PEBpMzN1aWg6ZmtqcjMzNGkzM0AwMC8yYDAuNS8xNmMyNTQuYSMyM2VecjQwMHFgLS1kLTBzcw%3D%3D", "download_url": "https://v9-default.365yg.com/ba4e13cee3720eaeaefac247d54e34c6/676bfea3/video/tos/cn/tos-cn-ve-15/ogsAHdnXeCAEOB7bp9GKABzApcOIEDQbgmweXD/?a=2011&br=1675&bt=1675&btag=80000e00008000&cd=0%7C0%7C0%7C0&ch=0&cr=0&cs=0&cv=1&dr=0&ds=4&dy_q=1735127175&dy_va_biz_cert=&feature_id=46a7bb47b4fd1280f3d3825bf2b29388&ft=k7Fz7VVywhiRF_80mo~pK7pswApoiT6ZvrK40zTmto0g3cI&l=202412251946156AD44F7BFBC7EE19A41E&mime_type=video_mp4&net=5&qs=0&rc=NDZpN2Q2ZjZkZDczZDc2PEBpMzN1aWg6ZmtqcjMzNGkzM0AwMC8yYDAuNS8xNmMyNTQuYSMyM2VecjQwMHFgLS1kLTBzcw%3D%3D", "image_url": "https://p11-sign.douyinpic.com/tos-cn-i-0813/ocDHztBsAhnDIdA6rAzgfC47E7eYAAduAAkA58~c5_300x400.jpeg?lk3s=138a59ce&x-expires=1736334000&x-signature=elDP1ycPh0oTuSthnNEAcxxG4pE%3D&from=327834062_large&s=PackSourceEnum_AWEME_DETAIL&se=false&sc=cover&biz_tag=aweme_video&l=2024122519461599C49874E8266D13A8F8" }, "tips": "接口由看戏仔-API（http://api.kxzjoker.cn/）免费提供", "time": "2024-12-25 19:46:16" }请求参数：参数名称是否必填备注内容url是短视频作品链接type=down否直接播放无水印视频返回参数：参数名称参数类型参数说明video_titlestring返回作品描述或标题video_urlstring视频链接download_urlstring视频下载链接image_urlstring返回封面图片链接访问返回：{ "success": 200, "data": { "video_title": "定格美好瞬间~#旅行#转场#甜妹", "video_url": "https://v9-default.365yg.com/1679d5cd6aecad83c0b731d1c0fda888/67862095/video/tos/cn/tos-cn-ve-15/ogsAHdnXeCAEOB7bp9GKABzApcOIEDQbgmweXD/?a=0&ch=0&cr=0&dr=0&net=5&cd=0%7C0%7C0%7C0&cv=1&br=1675&bt=1675&cs=0&ds=4&ft=k7Fz7VVywhiRF_80mo~pK7pswApt-o0ZvrK40zTmto0g3cI&mime_type=video_mp4&qs=0&rc=NDZpN2Q2ZjZkZDczZDc2PEBpMzN1aWg6ZmtqcjMzNGkzM0AwMC8yYDAuNS8xNmMyNTQuYSMyM2VecjQwMHFgLS1kLTBzcw%3D%3D&btag=80000e00008000&dy_q=1736839801&feature_id=46a7bb47b4fd1280f3d3825bf2b29388&l=2025011415300171284B75F58D3E465D5C", "download_url": "https://v9-default.365yg.com/1679d5cd6aecad83c0b731d1c0fda888/67862095/video/tos/cn/tos-cn-ve-15/ogsAHdnXeCAEOB7bp9GKABzApcOIEDQbgmweXD/?a=0&ch=0&cr=0&dr=0&net=5&cd=0%7C0%7C0%7C0&cv=1&br=1675&bt=1675&cs=0&ds=4&ft=k7Fz7VVywhiRF_80mo~pK7pswApt-o0ZvrK40zTmto0g3cI&mime_type=video_mp4&qs=0&rc=NDZpN2Q2ZjZkZDczZDc2PEBpMzN1aWg6ZmtqcjMzNGkzM0AwMC8yYDAuNS8xNmMyNTQuYSMyM2VecjQwMHFgLS1kLTBzcw%3D%3D&btag=80000e00008000&dy_q=1736839801&feature_id=46a7bb47b4fd1280f3d3825bf2b29388&l=2025011415300171284B75F58D3E465D5C", "image_url": "https://p11-sign.douyinpic.com/tos-cn-i-0813/ocDHztBsAhnDIdA6rAzgfC47E7eYAAduAAkA58~c5_300x400.jpeg?lk3s=138a59ce&x-expires=1738047600&x-signature=e%2BYpC4c5XvU5IRTczMpByWUPiXI%3D&from=327834062_large&s=PackSourceEnum_AWEME_DETAIL&se=false&sc=cover&biz_tag=aweme_video&l=202501141530016881D2CACDB1180188E1" }, "tips": "接口由看戏仔-API（http://api.kxzjoker.cn/）免费提供", "time": "2025-01-14 15:30:00" }
php随机播放视频api与前端代码 自适应版
Code：https://github.com/simtalk/random_videoindex.html： 回车按键：全屏/默认尺寸 方向键左右：切换视频 方向键上下：音量 空格：播放/暂停video.php 随机播放视频接口videos文件夹 放置视频进去就可以，支持子文件夹再此基础上，增加了手机端自适应宽高(左右和上下居中显示)的方法。电脑端设定的没有删除在 Your browser does not support the video tag. 连播关闭
本地图片API新建一个PHP文件（名字可以自己取），在创建一个img文件夹，把图片放进去。<?php $img_array = glob("img/*.{gif,jpg,png}",GLOB_BRACE); $img = array_rand($img_array); $dz = $img_array[$img]; header("Location:".$dz); ?>外链图片API新建一个PHP文件（名字可以自己取）， images.txt文档文件，把外链图片地址放进去。<?php $arr=file('images.txt'); $n=count($arr)-1; for ($i=1;$i<=1;$i++){ $x=rand(0,$n); header("Location:".$arr[$x],"\n"); } ?>本地视频API创建一个video的文件夹，视频放进去，和本地图片API差不多。<?php $video_array = glob("video/*.{mp4}",GLOB_BRACE); $video = array_rand($video_array); $dz = $video_array[$video]; header("Location:".$dz); ?>
一个php图片 api接口 每次打开加载不同的图片
1、准备图片资源首先需要在服务器上创建一个目录来存放你想要通过API提供的图片。比如，我们可以创建一个名为 images 的目录，并在其中放置一些图片文件。2、PHP脚本接下来，新建一个 PHP 脚本来处理请求，并随机选择一张图片发送给客户端。 PHP Code <?php // 设置图片目录 $imagesDir = 'images/'; // 获取目录中的所有图片文件 $images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE); // 检查是否有图片 if (empty($images)) { http_response_code(404); echo "No images found."; exit; } // 随机选择一张图片 $randomImage = $images[array_rand($images)]; // 设置图片头信息，这里假设图片是jpg，你可以根据文件扩展名设置 $fileType = pathinfo($randomImage, PATHINFO_EXTENSION); switch ($fileType) { case 'jpg': case 'jpeg': header('Content-Type: image/jpeg'); break; case 'png': header('Content-Type: image/png'); break; case 'gif': header('Content-Type: image/gif'); break; default: http_response_code(500); echo "Unsupported file type."; exit; } // 读取并输出图片内容 readfile($randomImage); 3、保存并上传PHP脚本将上述代码保存为一个PHP文件，比如命名为 api-image.php，并将其上传到你的web服务器上与 images 目录同级的目录中。4、访问API现在，你可以通过访问该PHP文件的URL来随机获取一张图片了。