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

如何获取iframe内YouTube视频的时长?求PHP/JS实现方案

Getting YouTube Video Duration from an Iframe (PHP vs JavaScript)

Hey there! Let's break down your options for grabbing the duration (in seconds) of that YouTube video in your iframe, and help you decide whether PHP or JavaScript is the right fit.

JavaScript Approach (Client-Side)

Since your iframe lives in the user's browser, JavaScript is the most direct way to get the duration in real-time. You'll use the official YouTube Iframe Player API to interact with the embedded video.

Here's how to implement it with your existing iframe:

<!-- Load the YouTube Iframe Player API first -->
<script src="https://www.youtube.com/iframe_api"></script>
<script>
  let videoPlayer;

  // This function is automatically called when the API loads
  function onYouTubeIframeAPIReady() {
    // Initialize the player using your iframe's ID ('video_player')
    videoPlayer = new YT.Player('video_player', {
      events: {
        'onReady': handlePlayerReady
      }
    });
  }

  // Triggered once the video player is ready
  function handlePlayerReady(event) {
    // Get the duration in seconds (returns a float; round if you need an integer)
    const durationInSeconds = videoPlayer.getDuration();
    console.log('Video Duration (seconds):', durationInSeconds);
    
    // Example: Display the duration on your page
    document.getElementById('duration-display').textContent = `Duration: ${Math.round(durationInSeconds)}s`;
  }
</script>

<!-- Add this element if you want to display the duration -->
<p id="duration-display"></p>

Pros of JavaScript:

  • No backend setup required
  • Real-time access to the video's duration once it loads
  • No API key needed (uses YouTube's official iframe API which is CORS-friendly)

PHP Approach (Server-Side)

If you need to fetch the duration before the page loads (e.g., to store it in a database, or generate content based on video length), use PHP with the YouTube Data API v3.

Steps to implement:

  1. Get a free API key from the Google Cloud Console (enable the YouTube Data API v3)
  2. Use the video ID from your iframe (0rVwuowU6Fs) to make an API request
  3. Parse the ISO8601 duration format into seconds

Here's the code:

<?php
// Replace with your actual YouTube Data API key
$apiKey = 'YOUR_GOOGLE_API_KEY';
$videoId = '0rVwuowU6Fs'; // Extracted from your iframe's src

// Fetch video metadata from YouTube API
$apiUrl = "https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id={$videoId}&key={$apiKey}";
$response = file_get_contents($apiUrl);
$videoData = json_decode($response, true);

if (isset($videoData['items'][0]['contentDetails']['duration'])) {
    $isoDuration = $videoData['items'][0]['contentDetails']['duration'];
    // Convert ISO8601 duration (e.g., PT1M30S) to total seconds
    $interval = new DateInterval($isoDuration);
    $totalSeconds = $interval->h * 3600 + $interval->i * 60 + $interval->s;
    
    echo "Video Duration (seconds): " . $totalSeconds;
} else {
    echo "Failed to retrieve video duration. Check your API key or video ID.";
}
?>

Pros of PHP:

  • Fetch duration before the page renders (useful for server-side logic)
  • Store the duration in a database to avoid repeated API calls

Note:

  • Keep your API key secure (don't expose it in frontend code)
  • YouTube Data API has request limits, so cache results if you're fetching multiple videos

Which Should You Choose?

  • Go with JavaScript if you need the duration for frontend interactions (displaying to users, syncing with UI elements, etc.)
  • Go with PHP if you need server-side access to the duration (pre-processing, storage, or generating dynamic content)

内容的提问来源于stack exchange,提问作者Adam Šulc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:36:32