MENU

短视频解析API接口汇总

May 5, 2025 • Read: 74 • Code

API仅供学习交流使用,禁止用于商业用途、违法用途等,否则后果自负!


功能特点

  • 支持多种短视频平台的链接解析
  • 快速获取视频相关信息
  • 返回结构化的 JSON 数据

直接使用(无需安装)

xxx.php 上传至 Web 服务器,通过 URL 访问:

http://你的服务器地址/xxx.php?url=目标链接

kuaishou.php(2025/5/7更新)

更新内容:

  • 修复部分链接无法解析问题
  • 优化解析速度
<?php
header('content-type:application/json; charset=utf-8');
// 格式化响应数据的函数
function formatResponse($code = 200, $msg = '解析成功', $data = [])
{
    return [
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ];
}


// 获取网页内容并解析 JSON 数据的函数
function kuaishou($url)
{
    // 定义请求头
    $headers = [
        'Cookie: 必填,
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0'
    ];
    $newurl = getRedirectedUrl($url);
    $response = '';
    $shortVideoPattern = '/short-video\/([^?]+)/';
    $photoPattern = '/photo\/([^?]+)/';

    if (preg_match($shortVideoPattern, $newurl, $matches)) {
        $id = $matches[1];
        $response = curl($url, $headers);
        while ($response === null) {
            $response = curl($url, $headers);
        }
    } elseif (preg_match($photoPattern, $newurl, $matches)) {
        $id = $matches[1];
        $response = curl("https://www.kuaishou.com/short-video/{$id}", $headers);
        while ($response === null) {
            $response = curl("https://www.kuaishou.com/short-video/{$id}", $headers);
        }
    }
    if ($response) {
        $apolloStatePattern = '/window\.__APOLLO_STATE__\s*=\s*(.*?)\<\/script>/s';
        if (preg_match($apolloStatePattern, $response, $matches)) {
            $functionPattern = '/function\s*\([^)]*\)\s*{[^}]*}/';
            $cleanedApolloState = preg_replace($functionPattern, ':', $matches[1]);
            $cleanedApolloState = preg_replace('/,\s*(?=}|])/', '', $cleanedApolloState);
            $charChainToRemove = ';(:());';
            $cleanedApolloState = str_replace($charChainToRemove, '', $cleanedApolloState);
            $cleanedApolloState = json_decode($cleanedApolloState, true);
            $videoInfo = $cleanedApolloState['defaultClient'] ?? null;
            if ($videoInfo) {
                $key = "VisionVideoDetailPhoto:{$id}";
                $json = $videoInfo[$key] ?? null;
                if ($json) {
                    $video_url = $json['photoUrl'];
                }
            }
        }
        if ($video_url) {
            $arr = array(
                'code' => 200,
                'msg' => '解析成功',
                'data' => array(
                    'title' => $json['caption'],
                    'cover' => $json['coverUrl'],
                    'url' => $video_url,
                )
            );
            return $arr;
        }
    }
}

function getRedirectedUrl($url)
{
    $ch = curl_init();
    // 设置请求的 URL
    curl_setopt($ch, CURLOPT_URL, $url);
    // 不返回响应体
    curl_setopt($ch, CURLOPT_NOBODY, true);
    // 跟随重定向
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    // 返回最终 URL
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // 禁用 SSL 验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    // 执行请求
    $result = curl_exec($ch);
    if ($result === false) {
        $error = curl_error($ch);
        curl_close($ch);
        trigger_error("cURL 执行出错: $error", E_USER_WARNING);
        return null;
    }

    // 获取重定向后的 URL
    $finalUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    // 关闭 cURL 会话
    curl_close($ch);
    return $finalUrl;
}

function curl($url, $header = null, $data = null)
{
    $con = curl_init((string)$url);
    curl_setopt($con, CURLOPT_HEADER, false);
    curl_setopt($con, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($con, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($con, CURLOPT_AUTOREFERER, 1);
    if (isset($header)) {
        curl_setopt($con, CURLOPT_HTTPHEADER, $header);
    }
    if (isset($data)) {
        curl_setopt($con, CURLOPT_POST, true);
        curl_setopt($con, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($con, CURLOPT_TIMEOUT, 5000);
    $result = curl_exec($con);
    return $result;
}

// 获取 URL 参数
$url = $_GET['url'] ?? '';
if (empty($url)) {
    echo json_encode(formatResponse(201, '链接不能为空!'), 480);
} else {
    $jsonData = kuaishou($url);
    if (isset($jsonData)) {
        echo json_encode(formatResponse(200, '解析成功', $jsonData), 480);
    } else {
        echo json_encode(formatResponse(404, '链接错误'), 480);
    }
}

bilibili.php

<?php

header('Content-type: text/json;charset=utf-8');
$urls = isset($_GET['url']) ? $_GET['url'] : '';
if (empty($urls)){
    exit(json_encode(['code' => 201, 'msg' => '链接不能为空!']));
}
$urls =cleanUrlParameters($urls);
$array = parse_url($urls);
if (empty($array)) {
    exit(json_encode(['code'=>-1, 'msg'=>"视频链接不正确"], 480));
}elseif ($array['host'] == 'b23.tv') {
    $header = get_headers($urls,true);
    $array = parse_url($header['Location']);
    $bvid = $array['path'];
}elseif ($array['host'] == 'www.bilibili.com') {
    $bvid = $array['path'];
}elseif ($array['host'] == 'm.bilibili.com') {
    $bvid = $array['path'];
}else{
    exit(json_encode(['code'=>-1, 'msg'=>"视频链接好像不太对!"], 480));
}
if (strpos($bvid, '/video/') === false) {
    exit(json_encode(['code'=>-1, 'msg'=>"好像不是视频链接"], 480));
}
$bvid = str_replace("/video/", "", $bvid);
//这里填写你的B站cookie(不填解析不到1080P以上) 格式为_uuid=XXXXX
$cookie = '写自己的cookie';
$header = ['Content-type: application/json;charset=UTF-8'];
$useragent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36';
//获取解析需要的cid值和图片以及标题
$json1 = bilibili(
    'https://api.bilibili.com/x/web-interface/view?bvid='.$bvid
    , $header
    , $useragent
    , $cookie
);
$array = json_decode($json1,true);
if($array['code'] == '0'){
    //循环获取
    foreach($array['data']['pages'] as $keys =>$pron){
        //对接上面获取cid值API来取得视频的直链
        $json2 = bilibili(
            "https://api.bilibili.com/x/player/playurl?otype=json&fnver=0&fnval=3&player=3&qn=112&bvid=".$bvid."&cid=".$pron['cid']."&platform=html5&high_quality=1"
            , $header
            , $useragent
            , $cookie
        );
        $array_2 = json_decode($json2,true);
        $bilijson[] = [
            'title' =>  $pron['part']
            ,'duration' => $pron['duration']
            ,'durationFormat' => gmdate('H:i:s', $pron['duration']-1)
            ,'accept' => $array_2['data']['accept_description']
            ,'video_url' =>  'https://upos-sz-mirrorhw.bilivideo.com/'.explode('.bilivideo.com/',$array_2['data']['durl'][0]['url'])[1]
        ];
    }
    $JSON = array(
        'code' => 1
    ,'msg' => '解析成功!'
    ,'title' => $array['data']['title']
    ,'imgurl' => $array['data']['pic']
    ,'desc' => $array['data']['desc']
    ,'data' => $bilijson
    ,'user' => [
            'name' => $array['data']['owner']['name']
            , 'user_img' => $array['data']['owner']['face']
        ]
    );
}else{
    $JSON = ['code'=>0, 'msg'=>"解析失败!"];
}
exit(json_encode($JSON,480));
function bilibili($url, $header, $user_agent, $cookie) {
    $ch = curl_init() ;
    curl_setopt($ch, CURLOPT_URL, $url );
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;
    curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
    curl_setopt($ch, CURLOPT_USERAGENT,$user_agent);
    curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ;
    $output = curl_exec($ch) ;
    curl_close ($ch);
    return $output;
}
function cleanUrlParameters($url) {
    // Step 1: 分解URL结构
    $parsed = parse_url($url);

    // Step 2: 构建基础组件(自动解码编码字符)
    $scheme   = isset($parsed['scheme']) ? $parsed['scheme'] . '://' : '';
    $host     = $parsed['host'] ?? '';
    $port     = isset($parsed['port']) ? ':' . $parsed['port'] : '';
    $path     = isset($parsed['path']) ? rawurldecode($parsed['path']) : '';
    $fragment = isset($parsed['fragment']) ? '#' . rawurldecode($parsed['fragment']) : '';

    // Step 3: 处理国际化域名(Punycode转中文)
    if (function_exists('idn_to_utf8') && preg_match('/^xn--/', $host)) {
        $host = idn_to_utf8($host, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46);
    }

    // Step 4: 移除认证信息(如 user:pass@)
    $host = preg_replace('/^.*@/', '', $host);

    // 去掉路径末尾的斜杠
    $path = rtrim($path, '/');

    // Step 5: 拼接最终URL
    return $scheme . $host . $port . $path . $fragment;
}
?>

weibo

<?php
header('content-type:application/json; charset=utf-8');
function weibo($url)
    {
        if (strpos($url, 'show?fid=') != false) {
            preg_match('/fid=(.*)/', $url, $id);
            $arr = json_decode(weibo_curl($id[1]), true);
        } else {
            preg_match('/\d+\:\d+/', $url, $id);
            $arr = json_decode(weibo_curl($id[0]), true);
        }
        if ($arr) {
            $one = key($arr['data']['Component_Play_Playinfo']['urls']);
            $video_url = $arr['data']['Component_Play_Playinfo']['urls'][$one];
            $arr = [
                'code' => 200,
                'msg' => '解析成功',
                'data' => [
                    'author' => $arr['data']['Component_Play_Playinfo']['author'],
                    'avatar' => $arr['data']['Component_Play_Playinfo']['avatar'],
                    'time' => $arr['data']['Component_Play_Playinfo']['real_date'],
                    'title' => $arr['data']['Component_Play_Playinfo']['title'],
                    'cover' => $arr['data']['Component_Play_Playinfo']['cover_image'],
                    'url' => $video_url
                ]
            ];
            return $arr;
        }
    }

function weibo_curl($id)
    {
        $cookie = "填自己的cookie";
        $post_data = "data={\"Component_Play_Playinfo\":{\"oid\":\"$id\"}}";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://weibo.com/tv/api/component?page=/tv/show/" . $id);
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        curl_setopt($ch, CURLOPT_REFERER, "https://weibo.com/tv/show/" . $id);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
$result = [];
$url = $_GET['url'];
if (empty($url)){
    $result = ['code' => 201, 'msg' => '链接不能为空!'];
} else {
    $info = weibo($url);
    // 检查 $info 是否为数组
    if (is_array($info) && $info['code'] == 200){
        $result = $info;
    } else{
        $result = ['code' => 404, 'msg' => '解析失败!'];
    }
}
echo json_encode($result, 480);
?>

douyin.php

<?php
header('Content-type: application/json');
function douyin($url)
{

    // 构造请求数据
    $header = array('User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1 Edg/122.0.0.0');
    // 尝试从 URL 中获取视频 ID
    $id = extractId($url);

    // 检查 ID 是否有效
    if (empty($id)) {
        // 访问当前链接获取跳转后的内容
        $response = curl($url, $header);
        // 假设跳转后的 URL 会在响应头中返回,这里获取跳转后的 URL
        $redirectUrl = getRedirectUrl($response);
        if ($redirectUrl) {
            // 尝试从跳转后的 URL 中获取视频 ID
            $id = extractId($redirectUrl);
        }
    }
    // 检查 ID 是否有效
    if (empty($id)) {
        return array('code' => 400, 'msg' => '无法解析视频 ID');
    }

    // 发送请求获取视频信息
    $response = curl('https://www.iesdouyin.com/share/video/' . $id, $header);
    $pattern = '/window\._ROUTER_DATA\s*=\s*(.*?)\<\/script>/s';
    preg_match($pattern, $response, $matches);

    if (empty($matches[1])) {
        return array('code' => 201, 'msg' => '解析失败');
    }

    $videoInfo = json_decode(trim($matches[1]), true);
    if (!isset($videoInfo['loaderData'])) {
        return array('code' => 201, 'msg' => '解析失败');
    }
    //替换 "playwm" 为 "play"
    $videoResUrl = str_replace('playwm', 'play', $videoInfo['loaderData']['video_(id)/page']['videoInfoRes']['item_list'][0]['video']['play_addr']['url_list'][0]);

    // 构造返回数据
    $arr = array(
        'code' => 200,
        'msg' => '解析成功',
        'data' => array(
            'author' => $videoInfo['loaderData']['video_(id)/page']['videoInfoRes']['item_list'][0]['author']['nickname'],
            'uid' => $videoInfo['loaderData']['video_(id)/page']['videoInfoRes']['item_list'][0]['author']['unique_id'],
            'avatar' => $videoInfo['loaderData']['video_(id)/page']['videoInfoRes']['item_list'][0]['author']['avatar_medium']['url_list'][0],
            'like' => $videoInfo['loaderData']['video_(id)/page']['videoInfoRes']['item_list'][0]['statistics']['digg_count'],
            'time' => $videoInfo['loaderData']['video_(id)/page']['videoInfoRes']['item_list'][0]["create_time"],
            'title' => $videoInfo['loaderData']['video_(id)/page']['videoInfoRes']['item_list'][0]['desc'],
            'cover' => $videoInfo['loaderData']['video_(id)/page']['videoInfoRes']['item_list'][0]['video']['cover']['url_list'][0],
            'url' => $videoResUrl,
            'music' => array(
                'author' => $videoInfo['loaderData']['video_(id)/page']['videoInfoRes']['item_list'][0]['music']['author'],
                'avatar' => $videoInfo['loaderData']['video_(id)/page']['videoInfoRes']['item_list'][0]['music']['cover_large']['url_list'][0]
            )
        )
    );
    return $arr;
}

function extractId($url)
{
    $headers = get_headers($url, true);
    if ($headers === false) {
        // 如果获取头信息失败,直接使用原始 URL
        $loc = $url;
    } else {
        // 处理重定向头可能是数组的情况
        if (isset($headers['Location']) && is_array($headers['Location'])) {
            $loc = end($headers['Location']);
        } else {
            $loc = $headers['Location'] ?? $url;
        }
    }

    // 确保 $loc 是字符串
    if (!is_string($loc)) {
        $loc = strval($loc);
    }

    preg_match('/[0-9]+/', $loc, $id);
    return !empty($id) ? $id[0] : null;
}

function getRedirectUrl($html)
{
    $pattern = '/<link data-react-helmet="true" rel="canonical" href="(.*?)"/';
    if (preg_match($pattern, $html, $matches)) {
        return $matches[1];
    }
    return null;
}
function curl($url, $header = null, $data = null)
{
    $con = curl_init((string)$url);
    curl_setopt($con, CURLOPT_HEADER, false);
    curl_setopt($con, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($con, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($con, CURLOPT_AUTOREFERER, 1);
    if (isset($header)) {
        curl_setopt($con, CURLOPT_HTTPHEADER, $header);
    }
    if (isset($data)) {
        curl_setopt($con, CURLOPT_POST, true);
        curl_setopt($con, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($con, CURLOPT_TIMEOUT, 5000);
    $result = curl_exec($con);
    if ($result === false) {
        // 处理 curl 错误
        $error = curl_error($con);
        curl_close($con);
        trigger_error("cURL error: $error", E_USER_WARNING);
        return false;
    }
    curl_close($con);
    return $result;
}
// 使用空合并运算符检查 url 参数
$url = $_GET['url']?? '';
if (empty($url)) {
    echo json_encode(['code' => 201, 'msg' => 'url为空'], 480);
} else {
    $response = douyin($url);
    if (empty($response)) {
        echo json_encode(['code' => 404, 'msg' => '获取失败'], 480);
    } else {
        echo json_encode($response, 480);
    }
}
?>

kuaishou.php

<?php
header('content-type:application/json; charset=utf-8');
// 格式化响应数据的函数
function formatResponse($code = 200, $msg = '解析成功', $data = [])
{
    return [
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ];
}


// 获取网页内容并解析 JSON 数据的函数
function kuaishou($url)
{
    // 定义请求头
    $headers = [
        'Accept: */*',
        'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'Cookie: 写自己的cookie',
        'Host: www.kuaishou.com',
        'Origin: https://www.kuaishou.com',
        'Pragma: no-cache',
        'Referer: https://www.kuaishou.com/new-reco',
        'Sec-Ch-Ua: "Microsoft Edge";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
        'Sec-Ch-Ua-Mobile: ?0',
        'Sec-Ch-Ua-Platform: "Windows"',
        'Sec-Fetch-Dest: empty',
        'Sec-Fetch-Mode: cors',
        'Sec-Fetch-Site: same-origin',
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0'
    ];
    $newurl = ksgetRedirectUrl($url);
    $pattern = '/short-video\/([^?]+)/';

    preg_match($pattern, $newurl, $matches);

    $id = $matches[1];

    $response = curl($url, $headers);
    while ($response == null) {
        $response = curl($url, $headers);
    }
    $pattern = '/window\.__APOLLO_STATE__\s*=\s*(.*?)\<\/script>/s';
    if (preg_match($pattern, $response, $matches)) {
        // 定义正则表达式匹配函数并移除
        $functionPattern = '/function\s*\([^)]*\)\s*{[^}]*}/';
        // ... existing code ...
        $cleanedApolloState = preg_replace($functionPattern, ':', $matches[1]);
        // 移除多余的逗号
        $cleanedApolloState = preg_replace('/,\s*(?=}|])/', '', $cleanedApolloState);
        // 移除特定字符链
        $charChainToRemove = ';(:());';
        $cleanedApolloState = str_replace($charChainToRemove, '', $cleanedApolloState);
        $cleanedApolloState = json_decode($cleanedApolloState, true);
        $videoInfo = $cleanedApolloState['defaultClient'] ?? null;
        $key = "VisionVideoDetailPhoto:{$id}";
        $json = $videoInfo["{$key}"];
        $video_url = $json['photoUrl'];
        if ($video_url) {
            $arr = array(
                'code' => 200,
                'msg' => '解析成功',
                'data' => array(
                    'title' => $json['caption'],
                    'cover' => $json['coverUrl'],
                    'url' => $video_url,
                )
            );
            return $arr;
        }
    }
}
function ksgetRedirectUrl($url)
{
    $ch = curl_init();

    $ch = initCurlOptions($ch, $url);
    curl_setopt($ch, CURLOPT_NOBODY, true);

    $result = curl_exec($ch);
    if ($result === false) {
        $error = curl_error($ch);
        curl_close($ch);
        throw new Exception("Curl error while getting redirect URL: $error");
    }

    $redirectUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    curl_close($ch);
    return $redirectUrl;
}
function initCurlOptions($ch, $url, $header = null, $data = null)
{
    // 确保 URL 是字符串类型
    $url = (string)$url;

    // 设置基本的 cURL 选项
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5000);

    // 设置请求头
    if (isset($header)) {
        if (!is_array($header)) {
            // 记录错误日志,方便调试
            error_log('initCurlOptions: $header 参数必须是数组类型');
            return false;
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }

    // 设置 POST 请求
    if (isset($data)) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    // 检查 cURL 选项设置是否成功
    if (curl_errno($ch)) {
        // 记录 cURL 错误信息
        $error = curl_error($ch);
        error_log("initCurlOptions: cURL 选项设置错误: $error");
        return false;
    }

    // 返回 cURL 句柄而非执行结果
    return $ch;
}
function curl($url, $header = null, $data = null)
{
    $con = curl_init((string)$url);
    curl_setopt($con, CURLOPT_HEADER, false);
    curl_setopt($con, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($con, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($con, CURLOPT_AUTOREFERER, 1);
    if (isset($header)) {
        curl_setopt($con, CURLOPT_HTTPHEADER, $header);
    }
    if (isset($data)) {
        curl_setopt($con, CURLOPT_POST, true);
        curl_setopt($con, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($con, CURLOPT_TIMEOUT, 5000);
    $result = curl_exec($con);
    return $result;
}
// 获取 URL 参数
$url = $_GET['url'] ?? '';
if (empty($url)) {
    echo json_encode(formatResponse(201, '链接不能为空!', []), 480);
} else {
    echo json_encode(kuaishou($url),480);
}

pipigx.php

<?php
// 设置响应头为 JSON 格式,使用 UTF-8 编码
header("content-type:application/json; charset=utf-8");

/**
 * 格式化响应信息
 * @param int $code 响应状态码
 * @param string $msg 响应消息
 * @param array $data 响应数据
 * @return array 格式化后的响应数组
 */
function formatResponse($code = 200, $msg = '解析成功', $data = [])
{
    return [
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ];
}

/**
 * 从 URL 中提取 pid 和 mid 参数
 * @param string $url 输入的 URL
 * @return array|false 包含 pid 和 mid 的数组,若提取失败则返回 false
 */
function extractParamsFromUrl($url)
{
    $parsedUrl = parse_url($url);
    if (!isset($parsedUrl['query'])) {
        return false;
    }
    parse_str($parsedUrl['query'], $params);
    $pid = $params['pid'] ?? null;
    $mid = $params['mid'] ?? null;
    if ($pid === null || $mid === null) {
        return false;
    }
    return ['pid' => $pid, 'mid' => $mid];
}

/**
 * 发送 POST 请求到指定 API
 * @param string $apiurl API 的 URL
 * @param array $payload 请求体数据
 * @return array|false 包含响应信息和状态码的数组,若请求失败则返回 false
 */
function sendPostRequest($apiurl, $payload)
{
    $jsonPayload = json_encode($payload);
    $headers = [
        'Content-Type: application/json',
        'Content-Length: '. strlen($jsonPayload)
    ];
    $ch = curl_init($apiurl);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if (curl_errno($ch)) {
        $error = curl_error($ch);
        curl_close($ch);
        return ['code' => 500, 'msg' => '请求发生错误: '. $error];
    }
    curl_close($ch);
    return ['code' => $httpCode, 'response' => $response];
}

/**
 * 处理 API 响应
 * @param array $apiResponse 包含 API 响应信息和状态码的数组
 * @return array 格式化后的响应数组
 */
function processApiResponse($apiResponse)
{
    $httpCode = $apiResponse['code'];
    $response = $apiResponse['response'];
    if ($httpCode >= 400) {
        return formatResponse($httpCode, 'HTTP 错误发生: HTTP 状态码 '. $httpCode);
    }
    $decodedResponse = json_decode($response, true);
    if ($decodedResponse === null) {
        return formatResponse(500, '响应内容不是有效的 JSON 数据: '. $response);
    }
    if (!isset($decodedResponse['data']['post'])) {
        return formatResponse(500, '响应中缺少 data.post 字段');
    }
    $json = $decodedResponse['data']['post'];
    $videoData = [];
    if (isset($json['videos']) && is_array($json['videos'])) {
        foreach ($json['videos'] as $video) {
            if (is_array($video)) {
                $videoData[] = $video;
            }
        }
    }
    $arr = [
        'title' => $json['content'],
        'cover' =>  "https://file.ippzone.com/img/frame/id/".($videoData[0]['thumb'] ?? ''),
        'video' => $videoData[0]['url']
    ];
    return formatResponse(200, '解析成功', $arr);
}

// 获取 URL 参数
$url = null;
if (isset($_GET['url'])) {
    $url = $_SERVER['REQUEST_URI'];
} elseif (isset($_POST['url'])) {
    $url = $_POST['url'];
}
if ($url === null) {
    http_response_code(400);
    echo json_encode(formatResponse(400, '未提供 url 参数'), 480);
    exit;
}

// 提取参数
$params = extractParamsFromUrl($url);
if ($params === false) {
    http_response_code(400);
    echo json_encode(formatResponse(400, '提取参数出错'), 480);
    exit;
}

// 构建请求体数据
$apiurl = 'https://h5.pipigx.com/ppapi/share/fetch_content';
$payload = [
    "pid" => (int)$params['pid'],
    "mid" => (int)$params['mid'],
    "type" => "post"
];

// 发送请求
$apiResponse = sendPostRequest($apiurl, $payload);
$finalResponse = processApiResponse($apiResponse);

// 设置 HTTP 状态码并输出响应
http_response_code($finalResponse['code']);
echo json_encode($finalResponse, 480);
?>

pipix.php

<?php
// 设置响应头为 JSON 格式
header('content-type:application/json; charset=utf-8');

// 定义常量
const MAX_REDIRECTS = 10;
const CURL_TIMEOUT = 5000;

// 初始化 CURL 选项
function initCurlOptions($ch, $url, $header = null, $data = null) {
    curl_setopt($ch, CURLOPT_URL, (string)$url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_MAXREDIRS, MAX_REDIRECTS);
    curl_setopt($ch, CURLOPT_TIMEOUT, CURL_TIMEOUT);

    if (isset($header)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }

    if (isset($data)) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    return $ch;
}

// 获取重定向后的 URL
function getRedirectUrl($url) {
    $ch = curl_init();
    $ch = initCurlOptions($ch, $url);
    curl_setopt($ch, CURLOPT_NOBODY, true);

    $result = curl_exec($ch);
    if ($result === false) {
        $error = curl_error($ch);
        curl_close($ch);
        throw new Exception("Curl error while getting redirect URL: $error");
    }

    $redirectUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    curl_close($ch);
    return $redirectUrl;
}

// 执行 CURL 请求
function curl($url, $header = null, $data = null) {
    $ch = curl_init();
    $ch = initCurlOptions($ch, $url, $header, $data);

    $result = curl_exec($ch);
    if ($result === false) {
        $error = curl_error($ch);
        curl_close($ch);
        throw new Exception("Curl error while making request: $error");
    }

    curl_close($ch);
    return $result;
}

function pipixia($url) {
    try {
        $url = getRedirectUrl($url);
        preg_match('/item\/(.*)\?/', $url, $id);
        if (!isset($id[1])) {
            return ['code' => 404, 'msg' => '无法从 URL 中提取视频 ID'];
        }

        $apiUrl = "https://h5.pipix.com/bds/cell/cell_h5_comment/?count=5&aid=1319&app_name=super&cell_id={$id[1]}";
        $response = curl($apiUrl);
        $arr = json_decode($response, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            return ['code' => 404, 'msg' => 'JSON 解析失败'];
        }

        if (is_array($arr) && isset($arr['data']['cell_comments'][1]['comment_info']['item'])) {
            $video_url = $arr['data']['cell_comments'][1]['comment_info']['item']['video']['video_high']['url_list'][0]['url'];
            $result = [
                'code' => 200,
                'msg' => '解析成功',
                'data' => [
                    'author' => $arr['data']['cell_comments'][1]['comment_info']['item']['author']['name'],
                    'avatar' => $arr['data']['cell_comments'][1]['comment_info']['item']['author']['avatar']['download_list'][0]['url'],
                    'title' => $arr['data']['cell_comments'][1]['comment_info']['item']['content'],
                    'cover' => $arr['data']['cell_comments'][1]['comment_info']['item']['cover']['download_list'][0]['url'],
                    'url' => $video_url
                ]
            ];
            return $result;
        } else {
            return ['code' => 404, 'msg' => '解析失败,未找到所需数据'];
        }
    } catch (Exception $e) {
        return ['code' => 404, 'msg' => '解析过程中出现错误: ' . $e->getMessage()];
    }
}

// 主程序
$result = [];
$url = isset($_GET['url']) ? $_GET['url'] : '';
if (empty($url)) {
    $result = ['code' => 201, 'msg' => '链接不能为空!'];
} else {
    $info = pipixia($url);
    $result = $info;
}

echo json_encode($result, 480);
?>

qsmusic.php

<?php
header('Content-type: text/json;charset=utf-8');
$url = (isset($_GET['url'])) ? $_GET['url'] : '';
$type = (isset($_GET['type'])) ? $_GET['type'] : 'json';
if ($type !== '' && $url !== '') {
    echo getMusicInfo($type, $url);
}else{
    echo json_encode(['code' => 404,'msg'=>'请补全参数'],480);
}

function getMusicInfo($type = 'json', $url = '')
{
    if (strstr($url, 'qishui.douyin.com')) {
        $url = headers($url);
        preg_match('/track_id=(\d+)/', $url, $match);
    } else {
        preg_match('/track_id=(\d+)/', $url, $match);
    }
    $curl = curl('https://music.douyin.com/qishui/share/track?track_id=' . $match[1]);

    // 匹配 application/ld+json 数据,获取标题和封面
    preg_match('/<script data-react-helmet="true" type="application\/ld\+json">(.*?)<\/script>/s', $curl, $ldJsonMatches);
    if (isset($ldJsonMatches[1])) {
        $ldJsonData = json_decode(urldecode($ldJsonMatches[1]), true);
        $title = $ldJsonData['title'] ?? '';
        $cover = isset($ldJsonData['images']) && count($ldJsonData['images']) > 0 ? $ldJsonData['images'][0] : '';
    } else {
        $title = '';
        $cover = '';
    }

    $jsJsonPattern = '/<script\s+async=""\s+data-script-src="modern-inline">_ROUTER_DATA\s*=\s*({[\s\S]*?});/';
    preg_match($jsJsonPattern, $curl, $jsJsonMatches);

    if (isset($jsJsonMatches[1])) {
        $jsonStr = $jsJsonMatches[1];
        $jsonData = json_decode(trim($jsonStr), true);
        if ($jsonData !== null && isset($jsonData['loaderData']['track_page']['audioWithLyricsOption']['url'])) {
            $musicUrl = $jsonData['loaderData']['track_page']['audioWithLyricsOption']['url'];
        } else {
            $musicUrl = '';
        }

        // 提取歌词 text 数据并按时间分割
        $lrcLyrics = [];
        if ($jsonData !== null && isset($jsonData['loaderData']['track_page']['audioWithLyricsOption']['lyrics']['sentences'])) {
            $sentences = $jsonData['loaderData']['track_page']['audioWithLyricsOption']['lyrics']['sentences'];
            foreach ($sentences as $sentence) {
                if (isset($sentence['startMs']) && isset($sentence['endMs']) && isset($sentence['words'])) {
                    $startMs = $sentence['startMs'];
                    $endMs = $sentence['endMs'];
                    $sentenceText = '';
                    foreach ($sentence['words'] as $word) {
                        if (isset($word['text'])) {
                            $sentenceText .= $word['text'];
                        }
                    }
                    // 将毫秒转换为 LRC 格式的时间标签
                    $minutes = floor($startMs / 60000);
                    $seconds = floor(($startMs % 60000) / 1000);
                    $milliseconds = $startMs % 1000;
                    $timeTag = sprintf("[%02d:%02d.%03d]", $minutes, $seconds, $milliseconds);
                    $lrcLyrics[] = $timeTag . $sentenceText;
                }
            }
        }
        // 将歌词数组拼接成字符串
        $lyrics = implode("\n", $lrcLyrics);
    } else {
        $musicUrl = '';
        $lyrics = '';
    }

    // 构建结果数组
    $info = array(
        'name' => $title,
        'url' => $musicUrl,
        'cover' => $cover,
        'lyrics' => $lyrics,
        'core' => '抖音汽水音乐解析',
        'copyright' => '接口编写:JH-Ahua 接口编写:JH-Ahua 2025-4-20'
    );

    if (!empty($info)) {
        return json_encode($info, 480);
    } else {
        return json_encode(array('msg' => '没有找到相关音乐'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }
}

//解析需要的参数 请勿乱动!
function curl($url, $data = '', $cookie = '', $headers = [])
{
    $con = curl_init((string)$url);
    curl_setopt($con, CURLOPT_HEADER, false);
    curl_setopt($con, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
    if (!empty($headers)) {
        curl_setopt($con, CURLOPT_HTTPHEADER, $headers);
    }
    if (!empty($cookie)) {
        curl_setopt($con, CURLOPT_COOKIE, $cookie);
    }
    if (!empty($data)) {
        curl_setopt($con, CURLOPT_POST, true);
        curl_setopt($con, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($con, CURLOPT_TIMEOUT, 5000);
    $result = curl_exec($con);
    return $result;
}

//取出真实链接!
function headers($url)
{
    $headers = get_headers($url, 1);
    if (isset($headers['Location'])) {
        if (is_array($headers['Location'])) {
            $url = end($headers['Location']);
        } else {
            $url = $headers['Location'];
        }
    }
    return $url;
}

?>

xhs.php

<?php
header('Content-type: application/json');

// 定义统一的输出函数
function output($code, $msg, $data = []) {
    return json_encode([
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ], 480);
}

function xhs($url) {
    // 构造请求数据
    $header = [
        'User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1 Edg/122.0.0.0'
    ];

    // 发送请求获取视频信息
    $response = curl($url, $header);
    if (!$response) {
        return output(400, '请求失败');
    }

    // 优化正则表达式
    $pattern = '/<script>\s*window.__INITIAL_STATE__\s*=\s*({[\s\S]*?})<\/script>/is';
    if (preg_match($pattern, $response, $matches)) {
        $jsonData = $matches[1];
        // 将 undefined 替换为 null
        $jsonData = str_replace('undefined', 'null', $jsonData);

        // 尝试将匹配到的字符串解析为 JSON
        $decoded = json_decode($jsonData, true);
        if ($decoded) {
            $videourl = $decoded['noteData']['data']['noteData']['video']['media']['stream']['h265'][0]['masterUrl'] ?? '';
            if ($videourl) {
                $data = [
                    'author' => $decoded['noteData']['data']['noteData']['user']['nickName'] ?? '',
                    'authorID' => $decoded['noteData']['data']['noteData']['user']['userId'] ?? '',
                    'title' => $decoded['noteData']['data']['noteData']['title'] ?? '',
                    'desc' => $decoded['noteData']['data']['noteData']['desc'] ?? '',
                    'avatar' => $decoded['noteData']['data']['noteData']['user']['avatar'] ?? '',
                    'cover' => $decoded['noteData']['data']['noteData']['imageList'][0]['url'] ?? '',
                    'url' => $videourl
                ];
                return output(200, '解析成功', $data);
            } else {
                return output(404, '解析失败,未获取到视频链接');
            }
        } else {
            return output(400, '匹配到的内容不是有效的 JSON 数据');
        }
    } else {
        return output(400, '未找到 JSON 数据');
    }
}

function curl($url, $header = null, $data = null) {
    $con = curl_init((string)$url);
    curl_setopt($con, CURLOPT_HEADER, false);
    curl_setopt($con, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($con, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($con, CURLOPT_AUTOREFERER, 1);
    if ($header) {
        curl_setopt($con, CURLOPT_HTTPHEADER, $header);
    }
    if ($data) {
        curl_setopt($con, CURLOPT_POST, true);
        curl_setopt($con, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($con, CURLOPT_TIMEOUT, 5000);
    $result = curl_exec($con);
    if ($result === false) {
        // 处理 curl 错误
        $error = curl_error($con);
        curl_close($con);
        trigger_error("cURL error: $error", E_USER_WARNING);
        return false;
    }
    curl_close($con);
    return $result;
}

// 获取请求参数
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $url = $_GET['url']?? null;
} else {
    $url = $_POST['url']?? null;
}
if (empty($url)) {
    echo output(201, 'url 为空');
} else {
    echo xhs($url);
}
?>


Last Modified: May 8, 2025
Archives QR Code Tip
QR Code for this page
Tipping QR Code