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

PHP中获取数组子元素问题:如何从YouTube Data API的JSON响应中提取视频详情

解决YouTube Data API JSON解析中提取视频详情的问题

Hey there! Let's work through how to pull those video details like publishedAt and title from the YouTube Data API response in PHP—you're already halfway there with your current code, just need to adjust how you access the nested data.

Why you can't access the items sub-elements right now

The items field in the API response is an array of video objects, not a single value. When you try to directly reference it like you do with top-level fields, you'll just get an Array output instead of the actual video details. You need to either loop through the array to process all videos, or target a specific video by its index.

Step-by-step solution to extract video details

Let's update your code to safely access and parse the nested data, with error handling to avoid unexpected issues:

// Fetch the API response
$apiResponse = file_get_contents($url);

// Check if the request was successful
if ($apiResponse === false) {
    die("Failed to fetch data from YouTube API—check your URL, API key, or network connection.");
}

// Parse JSON into an associative array
$responseData = json_decode($apiResponse, true);

// Verify JSON parsing worked
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON parsing failed: " . json_last_error_msg());
}

// Check if the items array exists and has content
if (!empty($responseData['items'])) {
    // Loop through each video in the items array
    foreach ($responseData['items'] as $video) {
        // Extract nested video details from the "snippet" object
        $publishedAt = $video['snippet']['publishedAt'];
        $title = $video['snippet']['title'];
        $description = $video['snippet']['description'];
        
        // Get the video ID (adjust based on your API endpoint):
        // For playlistItems.list (fetching uploaded videos):
        $videoId = $video['snippet']['resourceId']['videoId'];
        // For search.list (general video search):
        // $videoId = $video['id']['videoId'];

        // Output or process the data
        echo "<strong>Title:</strong> $title<br>";
        echo "<strong>Published:</strong> $publishedAt<br>";
        echo "<strong>Video ID:</strong> $videoId<br><br>";
    }
} else {
    echo "No video data found in the API response.";
}

A cleaner alternative: Object-oriented parsing

Instead of converting JSON to an associative array, you can parse it into a PHP object (skip the true parameter in json_decode). This makes accessing nested properties feel more intuitive with the -> operator:

$apiResponse = file_get_contents($url);
if ($apiResponse === false) {
    die("Failed to fetch API data.");
}

$responseObj = json_decode($apiResponse);
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON parsing error: " . json_last_error_msg());
}

if (!empty($responseObj->items)) {
    foreach ($responseObj->items as $video) {
        $title = $video->snippet->title;
        $publishedAt = $video->snippet->publishedAt;
        $videoId = $video->snippet->resourceId->videoId;

        echo "Title: $title | Published: $publishedAt<br>";
    }
}

Key tips to avoid issues

  • Always add error handling for file_get_contents and json_decode—API requests can fail, or JSON might be malformed.
  • Use var_dump($responseData) or print_r($responseData) to print the full response structure if you're unsure about nested paths.
  • Different YouTube Data API endpoints return slightly different structures (e.g., search.list vs playlistItems.list), so adjust the paths to fields like videoId accordingly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 08:52:47