You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在网站上显示YouTube视频播放量?现有代码无法实现

问题诊断与修复方案

你的代码存在几个核心问题,导致播放量无法正常显示:

1. 前端调用的YouTube API已废弃

你前端代码里的gdata.youtube.com是旧版GData API,早在2015年就被官方弃用,现在完全无法返回有效数据,这是前端获取播放量失败的根本原因。

2. PHP提取视频ID的方式不可靠

substr($_GET['url'], -11)只能处理youtu.be/VIDEO_ID这类短链接,遇到带参数的URL(比如youtube.com/watch?v=VIDEO_ID&t=10s)时,提取的内容会包含参数,直接导致API请求失败。

3. file_get_contents存在兼容性限制

部分服务器会关闭allow_url_fopen配置,导致无法通过该函数获取远程API数据。


修复后的完整代码

下面是修正后的代码,统一通过后端PHP调用官方支持的YouTube Data API v3获取播放量,兼容多种URL格式,同时添加了完整的错误处理:

<!DOCTYPE html>
<html>
<head>
    <title>YouTube Video View Counter</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        function videoViews() {
            const videoUrl = $('input').val().trim();
            if (!videoUrl) {
                alert('请输入有效的YouTube视频链接');
                return;
            }

            // 前端先验证并提取视频ID
            const rex = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/;
            const videoIdMatch = videoUrl.match(rex);
            if (!videoIdMatch) {
                alert('无法识别视频ID,请检查链接格式');
                return;
            }
            const videoId = videoIdMatch[1];

            // 嵌入视频
            const embedUrl = `//www.youtube.com/embed/${videoId}`;
            const embedCode = `<iframe width="350" height="197" src="${embedUrl}" frameborder="0" allowfullscreen></iframe>`;
            $('.videoembed').html(embedCode);

            // 调用后端接口获取播放量
            $.get(`?url=${encodeURIComponent(videoUrl)}`, function(response) {
                if (response.success) {
                    $('.views').text(`播放量:${response.views}`);
                } else {
                    $('.views').text(`获取失败:${response.message}`);
                }
            }, 'json');
        }
    </script>
</head>
<body>
    <input type="url" placeholder="输入YouTube视频URL"> 
    <a href="#" onClick="videoViews(); return false;">GO</a>
    
    <div class="videoembed"></div>
    <div class="views"></div>

    <?php
    if(isset($_GET['url'])) {
        $videoUrl = $_GET['url'];
        // 用正则兼容所有常见YouTube URL格式,提取视频ID
        $pattern = '/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/';
        preg_match($pattern, $videoUrl, $matches);
        
        if(!isset($matches[1])) {
            echo json_encode(['success' => false, 'message' => '无效的视频链接']);
            exit;
        }
        $videoId = $matches[1];

        // 替换为你自己的YouTube Data API v3密钥
        $apiKey = 'AIzaSyAGquK-QPs8yaddEqhL1AEmYbrJKT6xs04';
        $apiUrl = "https://www.googleapis.com/youtube/v3/videos?part=statistics&id={$videoId}&key={$apiKey}";

        // 使用cURL替代file_get_contents,避免服务器配置限制
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 生产环境建议开启SSL验证
        $response = curl_exec($ch);
        curl_close($ch);

        if(!$response) {
            echo json_encode(['success' => false, 'message' => '无法连接到API服务器']);
            exit;
        }

        $data = json_decode($response, true);
        if(empty($data['items']) || !isset($data['items'][0]['statistics']['viewCount'])) {
            echo json_encode(['success' => false, 'message' => '视频不存在或API密钥无效']);
            exit;
        }

        $views = number_format($data['items'][0]['statistics']['viewCount']);
        echo json_encode(['success' => true, 'views' => $views]);
        exit;
    }
    ?>
</body>
</html>

关键修改说明

  • 替换废弃API:彻底移除旧版GData API调用,改用官方支持的YouTube Data API v3。
  • 可靠提取视频ID:用正则表达式兼容所有常见YouTube URL格式,确保11位视频ID提取准确。
  • 改用cURL:避免file_get_contents的服务器配置限制,提升代码兼容性。
  • 错误处理:添加多环节的错误判断,返回清晰的错误提示,方便排查问题。
  • 播放量格式化:用number_format给播放量添加千位分隔符,提升可读性。

注意事项

  1. 确保你的API密钥已启用YouTube Data API v3服务,免费配额为每天10000次请求。
  2. 不要在公开代码中暴露API密钥,生产环境建议将密钥存储在独立配置文件中。
  3. 生产环境请开启CURLOPT_SSL_VERIFYPEER,保障HTTPS请求的安全性。

内容的提问来源于stack exchange,提问作者Maheshi Chathurika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 12:13:09