Classe php para importar informações de um vídeo do youtube (Vídeo-aula)

3

Publicado em : 25/01/2012 | Por : Rafael Wendel Pinheiro | Em : classes, php, tutorial, video-aulas
  • Tags: , , ,
  • Olá pessoal! Faz tempo que não posto nada devido às festividades e viagens de final de ano mas finalmente hoje iniciarei o 2012 aqui no blog.

    E nada melhor para celebrar um novo ano do que uma vídeo-aula feita sobre medida para vocês que estão sempre por aqui.

    E nessa vídeo-aula eu apresento uma classe php que criei e que tem como objetivo buscar informações de um determinado vídeo do Youtube, como descrição, tags, imagem, tipo e etc, tudo via CURL. Além dessas informações a classe é capaz de devolver o código de incorporação (embed) do vídeo.

    Abaixo está o vídeo e logo a seguir o código da classe.

    Obs: Peço desculpas pois na hora de converter o vídeo no camtasia ele cortou algumas partes nas laterais. Mas dá para acompanhar tranquilo.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    
    <?php
    /**
     * Classe de integração que importa as tags e o embed de um vídeo do Youtube
     *
     * @author Rafael Wendel Pinheiro <rafaelwendel@hotmail.com> <www.rafaelwendel.com>
     * @version 1.0
     */
    class Youtube {
     
         /**
         * URL do vídeo no Youtube
         * @access private
         * @var String
         */
        private $link;
     
        /**
         * Armazena as tags referentes ao vídeo
         * @access private
         * @var array
         */
        private $tags = array();
     
        /**
         * Armazena informações referentes à erros
         * @access private
         * @var array
         */
        private $erro = array();
     
     
        /**
         * Método construtor da classe Youtube.
         * @access public
         * @param String $link URL do vídeo no Youtube (OBS: Não utilize URL encurtada)
         * @return void
         */
        public function __construct($link = '') {
            if($link != ''){
                $this->setLink($link);
                $this->loadTags();
            }
        }
     
        /**
         * Pegar a URL do vídeo que está sendo utilizado
         * @access public
         * @return String a URL do vídeo
         */
        public function getLink() {
            return $this->link;
        }
     
        /**
         * Definir a URL do vídeo no Youtube
         * @access public
         * @param String $link a URL do vídeo
         * @return mixed false em caso de URL inválida
         */
        public function setLink($link) {
            if(!strstr($link, "youtube.com")){
                $this->setErro('URL inválida');
                return false;
            }
            $this->link = $link;
        }
     
        /**
         * Capturar o(s) erro(s)
         * @access public
         * @return Array
         */
        public function getErro() {
            return $this->erro;
        }
     
     
        /**
         * Definir uma mensagem de erro
         * @access public
         * @param String $erro
         * @return void
         */
        public function setErro($erro) {
            $this->erro[] = $erro;
        }
     
        /**
         * Armazena as tags importadas na variável $tags
         * @access private
         * @param Array $tags
         * @return void
         */
        private function setTags($tags){
            if(is_array($tags)){
                foreach($tags as $prop => $value){
                   $this->tags[$prop] = $value;
                }
                $this->repairTags();
            }
        }
     
        /**
         * Capturar as tags do vídeo
         * @access public
         * @return mixed Arrays com tags ou false em caso de array vazio
         */
        public function getTags() {
            if(count($this->tags) > 0){
                return $this->tags;
            }
            else{
                return false;
            }
        }
     
        /**
         * Chamar a execução da URL e setar as tags em caso de sucesso
         * @access private
         * @return mixed False em casso de erros
         */
        private function loadTags() {
            if(empty ($this->link)){
                $this->setErros('URL inválida');
                return false;
            }
            $propertys = $this->get_propertys_tags();
            if(in_array('noindex', $propertys)){
                $this->setErro('URL inválida');
                return false;
            }
            $this->setTags($propertys);
        }
     
        /**
         * Repara os nomes dos indices do array $tags
         * @access private
         * @return void
         */
        private function repairTags(){
            if(count($this->tags) > 0){
                $tags = $this->tags;
                foreach ($tags as $prop => $value){
                    $nome = explode(':', $prop);
                    $nome = $nome[count($nome) - 1];
     
                    $new[$nome] = $value;
                }
                $this->tags = $new;
            }
        }
     
        /**
         * Pega o conteúdo do link do Youtube via CURL
         * @access private
         * @return String $data Conteúdo lido
         */
        private function file_get_contents_curl(){
            $ch = curl_init();
     
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_URL, $this->link);
     
            $data = curl_exec($ch);
            curl_close($ch);
     
            return $data;
        }
     
        /**
         * Lê o conteúdo recuperado e extrai as tags do vídeo
         * @access private
         * @return Array As Tags do vídeo
         */
        private function get_propertys_tags(){
            $html = $this->file_get_contents_curl();
     
            $doc = new DOMDocument();
            @$doc->loadHTML($html);
     
            $metas = $doc->getElementsByTagName('meta');
            for ($i = 0; $i < $metas->length; $i++){
                $meta = $metas->item($i);
                $prop_tags[$meta->getAttribute('property')] = $meta->getAttribute('content');
            }
            return $prop_tags;
        }
     
        /**
         * Retorna o código de incorporação do video
         * @param int $width largura do embed
         * @param int $height altura do embed
         * @return String Código embed do vídeo
         */
        public function get_embed_video($width = 396, $height = 297){
            $cod_video = explode('watch?v=', $this->link);
            $cod_video = $cod_video[1];
            return "<iframe width=\"$width\" height=\"$height\" src=\"http://www.youtube.com/embed/$cod_video\" frameborder=\"0\" allowfullscreen></iframe>";
        }
    }

    Siga-me no twitter: @rafaelwendel

    Posts relacionados:

    Rafael Wendel Pinheiro

    facebooktwittergoogle plus

    É formado em Sistemas de Informação e pós-graduado em Sistemas de Banco de Dados. Trabalha com o desenvolvimento de sites, sistemas e outras soluções web.


    Comentários

    falai Rafael, beleza?

    então testei o teu script e dá erro na linha 159:
    Fatal error: Call to undefined function curl_init() in D:\wamp\www\pegaVideo\youtube.class.php on line 159

    deu certo Rafael, o cURL tava desativado rsrs..

    posso dar uma opinião?

    na linha 197 e 198
    trocar por isso:
    parse_str(parse_url($this->link, PHP_URL_QUERY));

    ai no iframe tu só coloca a variável $v.

    fica assim:

    public function get_embed_video($width = 396, $height = 297){
    // pega o id do vídeo usando a variavel $v
    parse_str(parse_url($this->link, PHP_URL_QUERY));
    return “”;
    }

    aprendi isso hoje, na net… e decidi compartilhar com você que essa classe é demais.

    valeu

    Olá Junior,

    Valeu demais pela dica. Com certeza irei fazer a alteração.

    Abs

    Deixe um comentário