Youtube api哪里会写这段代码

时间:2014-03-30 20:15:16

标签: youtube-api

我的PHP知识太糟糕了。我正在使用YouTube-api。会写下这段代码:Retrieve Youtube Channel info for "Vanity" channel

1 个答案:

答案 0 :(得分:0)

如果你在谈论这一行:

GET https://www.googleapis.com/youtube/v3/channels?part=snippet%2CcontentDetails%2Cstatistics&id=UC6ltI41W4P14NShIBHU8z1Q&key={YOUR_API_KEY}

您只是在提出请求,您可以使用file_get_contents为您获取回复:

$response = file_get_contents("https://www.googleapis.com/youtube/v3/channels?part=snippet%2CcontentDetails%2Cstatistics&id=UC6ltI41W4P14NShIBHU8z1Q&key={YOUR_API_KEY}");

两个注释:

  • 您必须使用开发人员密钥替换{YOUR_API_KEY}。您可以从youtube轻松申请:http://code.google.com/apis/youtube/dashboard/

  • 这只是一行代码中的一个示例,我建议您使用更好的方法来发出此请求,如下所示:

    // Encode the parameters of the link
    function encode_param($params) {
        foreach ($params as $field => $value){
            $encoded_params[] = $field . '=' . urlencode($value);
        }
        return $encoded_params;
    }
    
    // Get the response
    function get_response($url) {
        $response = file_get_contents($url);
        // If error, send message back to the client
        if ($response === false) {
            exit("Couldn't get response from the api");
        }
        return $response;
    }
    
    $params = array(
            "part" => "snippet,contentDetails,statistics",
            "id"   => "UC6ltI41W4P14NShIBHU8",
            "key"  => "-----------", // Your API key
    );
    
    $encoded_params = encode_param($params);
    $request_url = "https://www.googleapis.com/youtube/v3/channels?".implode('&', $encoded_params);
    $response = get_response($request_url);
    
    //............