web-dev-qa-db-ja.com

YouTubeのビデオタイムを取得するための関数を作成する方法

Tom J NowellがYouTubeのビデオの時間を取得するのに役立つようにこのコードを投稿しました。

関数

// function to parse the code from the URL
function parse_youtube_video_id_from_url( $video_url ) {
    $splited_data = explode( '=', $video_url );
    $video_unique_code = substr( $splited_data[1], 0, -strlen( strrchr( $splited_data[1], '&' ) ) );
    return $video_unique_code;
}

// use the youtube APIs to get a json string containing data about the video
function get_youtube_json_video_data( $video_code ) {
    $api_url = 'https://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc&q='.$video_code;
    $data = wp_remote_get( $api_url );
    return $data['body'];
}

データを取得する:

<?php $youtubecode = 'QiNIfGiNiOk';
$video_data = get_youtube_json_video_data($youtubecode);
$video_data = json_decode( $video_data ); 
echo '<pre>'.print_r($video_data,true).'</pre>';
?>

上記のコードが取得するデータ(例)

stdClass Object
(
    [apiVersion] => 2.1
    [data] => stdClass Object
        (
            [updated] => 2013-02-27T18:29:22.395Z
            [totalItems] => 1
            [startIndex] => 1
            [itemsPerPage] => 25
            [items] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => QiNIfGiNiOk
                            [uploaded] => 2012-11-30T18:20:08.000Z
                            [updated] => 2013-02-26T22:33:56.000Z
                            [uploader] => ramonsteck
                            [category] => Entertainment
                            [title] => After Earth - Trailer 2013
                            [description] => Unete www.facebook.com/Cinemovs Historias Paranormales Reales, Películas de Terror Online y proximos estrenos de cine.
                            [thumbnail] => stdClass Object
                                (
                                    [sqDefault] => http://i.ytimg.com/vi/QiNIfGiNiOk/default.jpg
                                    [hqDefault] => http://i.ytimg.com/vi/QiNIfGiNiOk/hqdefault.jpg
                                )

                            [player] => stdClass Object
                                (
                                    [default] => https://www.youtube.com/watch?v=QiNIfGiNiOk&feature=youtube_gdata_player
                                    [mobile] => https://m.youtube.com/details?v=QiNIfGiNiOk
                                )

                            [content] => stdClass Object
                                (
                                    [5] => https://www.youtube.com/v/QiNIfGiNiOk?version=3&f=videos&app=youtube_gdata
                                    [1] => rtsp://v1.cache6.c.youtube.com/CiILENy73wIaGQnpiI1ofEgjQhMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
                                    [6] => rtsp://v1.cache6.c.youtube.com/CiILENy73wIaGQnpiI1ofEgjQhMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
                                )

                            [duration] => 123
                            [aspectRatio] => widescreen
                            [rating] => 2.6722891
                            [likeCount] => 174
                            [ratingCount] => 415
                            [viewCount] => 247218
                            [favoriteCount] => 0
                            [commentCount] => 63
                            [accessControl] => stdClass Object
                                (
                                    [comment] => allowed
                                    [commentVote] => allowed
                                    [videoRespond] => moderated
                                    [rate] => allowed
                                    [embed] => allowed
                                    [list] => allowed
                                    [autoPlay] => allowed
                                    [syndicate] => allowed
                                )

                        )

                )

        )

)

動画の再生時間を取得するにはどうすればよいですか(例: '1:23')。

彼は私にこう言った:

関数を作成し、その関数を 'save_post'アクションと 'publish_post'アクションにフックして、上記のコードに基づいて投稿メタ/カスタムフィールドを更新する

どのように私はその関数フックを作成することができますか?そしてどのように私はまとめることができます:

カスタムフィールドは私がキーを置いたのです:

<?php $key="trailer"; echo get_post_meta($post->ID, $key, true); ?>

動画データを取得するには、次のようにYouTubeのURLコードを指定します。

$youtubecode = 'QiNIfGiNiOk';

-------------------------- UPDATE - 動作するコード------------------ -------

<?php 
$key="trailer";
$youtubecode = get_post_meta($post->ID, $key, true);
$video_data = get_youtube_json_video_data($youtubecode);
$video_data = json_decode( $video_data ); 
foreach ( $video_data->data->items as $data ){
                echo brsfl_secondsToTime($data->duration);
    }
?>

--------------------------------- Brasofiloに感謝します-------------- --------------

1
Batman

以下は、私がwp_remote_getに対するYouTubeの応答からデータを抽出するために使用する関数です。

それは単なる基本的なことです、あなたはあなたのコードを調整し、補完しそして統合しなければならないでしょう。

add_action( 'save_post', 'brsfl_save_postdata' );

function brsfl_save_postdata( $post_id ) 
{
    // IMPORTANT!
    // Check for DOING_AUTOSAVE and wp_verify_nonce()

    $consult = brsfl_yt_api( $_POST['yt_id'] );
    if( $consult )
    {
        $youtube['yt_time'] = $consult['yt_time'];
        $youtube['yt_likes'] = $consult['yt_likes'];
        $youtube['yt_dislikes'] = $consult['yt_dislikes'];
        $youtube['yt_average'] = $consult['yt_average'];
        $youtube['yt_raters'] = $consult['yt_raters'];
        $youtube['yt_viewcount'] = $consult['yt_viewcount'];
        $youtube['yt_title'] = $consult['yt_title'];
        $youtube['yt_thumb'] = $consult['yt_thumb'];
        update_post_meta( $post_id, 'youtube', $youtube );
    }   
}


/** 
 * Consult YouTube API
 * https://developers.google.com/youtube/2.0/developers_guide_protocol_video_entries
 */
function brsfl_yt_api( $video_id ) 
{
    // get Video Info
    $youtube = wp_remote_get( 
        'https://gdata.youtube.com/feeds/api/videos/'
        . $video_id
        . '?v=2&alt=json',

        array(
             'timeout' => 120, 
            'httpversion' => '1.1' 
        ) 
    );

    // Full response: https://Gist.github.com/e5a8cda8141b10711ad2
    if ( $youtube['response']['code'] == '200' )
    {
        $youtube_array = json_decode( $youtube['body'], true );
        $mediagroup = $youtube_array['entry']['media$group'];
        $yt_rating  = $youtube_array['entry']['yt$rating'];
        $yt_stats   = $youtube_array['entry']['yt$statistics'];
        $Gd_rating  = $youtube_array['entry']['Gd$rating'];

        $return['yt_time']      = brsfl_secondsToTime( $mediagroup['yt$duration']['seconds'] );
        $return['yt_likes']     = $yt_rating['numLikes'];
        $return['yt_dislikes']  = $yt_rating['numDislikes'];
        $return['yt_average']   = $Gd_rating['average'];
        $return['yt_raters']    = $Gd_rating['numRaters'];
        $return['yt_viewcount'] = $yt_stats['viewCount'];
        $return['yt_title']     = $youtube_array['entry']['title']['$t'];
        $return['yt_thumb']     = $mediagroup['media$thumbnail'][1]['url'];

        return $return;
    }   
    return false;
}


/** 
 * Convert seconds to timecode
 * http://stackoverflow.com/q/8273804
 */
function brsfl_secondsToTime($inputSeconds) 
{

    $secondsInAMinute = 60;
    $secondsInAnHour  = 60 * $secondsInAMinute;
    $secondsInADay    = 24 * $secondsInAnHour;

    // extract days
    $days = floor($inputSeconds / $secondsInADay);

    // extract hours
    $hourSeconds = $inputSeconds % $secondsInADay;
    $hours = floor($hourSeconds / $secondsInAnHour);

    // extract minutes
    $minuteSeconds = $hourSeconds % $secondsInAnHour;
    $minutes = floor($minuteSeconds / $secondsInAMinute);

    // extract the remaining seconds
    $remainingSeconds = $minuteSeconds % $secondsInAMinute;
    $seconds = ceil($remainingSeconds);

    // DAYS
    if( (int)$days == 0 )
        $days = '';
    elseif( (int)$days < 10 )
        $days = '0' . (int)$days . ':';
    else
        $days = (int)$days . ':';

    // HOURS
    if( (int)$hours == 0 )
        $hours = '';
    elseif( (int)$hours < 10 )
        $hours = '0' . (int)$hours . ':';
    else 
        $hours = (int)$hours . ':';

    // MINUTES
    if( (int)$minutes == 0 )
        $minutes = '';
    elseif( (int)$minutes < 10 )
        $minutes = '0' . (int)$minutes . ':';
    else 
        $minutes = (int)$minutes . ':';

    // SECONDS
    if( (int)$seconds == 0 )
        $seconds = '00';
    elseif( (int)$seconds < 10 )
        $seconds = '0' . (int)$seconds;

    return $days . $hours . $minutes . $seconds;
}
1
brasofilo