使用php脚本获取youtube标题


Get youtube title with php script

我想在一个变量中获得youtube视频的标题,但我尝试的所有方法都不起作用。下面代码的一部分返回变量$output中的标题片段:

{"items":[{"snippet":{"title":"2016迈阿密超级音乐节哈德威尔现场直播"

但是,我怎么可能只得到变量中的标题呢?

<?php

function curl_download($Url){
    // is cURL installed yet?
    if (!function_exists('curl_init')){
        die('Sorry cURL is not installed!');
    }
    // OK cool - then let's create a new cURL resource handle
    $ch = curl_init();
    // Now set some options (most are optional)
    // Set URL to download
    curl_setopt($ch, CURLOPT_URL, $Url);

    // Include header in result? (0 = yes, 1 = no)
    curl_setopt($ch, CURLOPT_HEADER, 0);
    // Should cURL return or print out the data? (true = return, false = print)
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // Timeout in seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    // Download the given URL, and return output
    $output = curl_exec($ch);
    // Close the cURL resource, and free system resources
    curl_close($ch);
    return $output;
}
$response = curl_download('https://www.googleapis.com/youtube/v3/videos?id=m1ssAFzaCsU&key=AIzaSyBj5GoJlQ4XzebaG6H2tp_WVuQ03JEOOss&fields=items(snippet(title))&part=snippet');
if ($response) {
    $xml   = new SimpleXMLElement($response);
    $title = (string) $xml->title;
    echo $title;
} else {
    // Error handling.
                echo 'error';
}
?>

$output是一个JSON字符串,使用JSON_decode解析:

$output = '{ "items": [ { "snippet": { "title": "Hardwell Live at Ultra Music Festival Miami 2016" } } ] }';
$output_decoded = json_decode($output);
$title = $output_decoded->items[0]->snippet->title;
// $title is now 'Hardwell Live at Ultra Music Festival Miami 2016';

适用于您的代码:

<?php

function curl_download($Url){
    // is cURL installed yet?
    if (!function_exists('curl_init')){
        die('Sorry cURL is not installed!');
    }
    // OK cool - then let's create a new cURL resource handle
    $ch = curl_init();
    // Now set some options (most are optional)
    // Set URL to download
    curl_setopt($ch, CURLOPT_URL, $Url);

    // Include header in result? (0 = yes, 1 = no)
    curl_setopt($ch, CURLOPT_HEADER, 0);
    // Should cURL return or print out the data? (true = return, false = print)
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // Timeout in seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    // Download the given URL, and return output
    $output = curl_exec($ch);
    // Close the cURL resource, and free system resources
    curl_close($ch);
    return $output;
}
$response = curl_download('https://www.googleapis.com/youtube/v3/videos?id=m1ssAFzaCsU&key=AIzaSyBj5GoJlQ4XzebaG6H2tp_WVuQ03JEOOss&fields=items(snippet(title))&part=snippet');
if ($response) {
    $response_decoded = json_decode($response);
    $title = $response_decoded->items[0]->snippet->title;
    echo $title;
} else {
    // Error handling.
                echo 'error';
}
?>