web-dev-qa-db-fra.com

API YouTube - Extraire l'ID vidéo

Je code une fonctionnalité qui permet aux utilisateurs d'entrer une URL de vidéo Youtube. Je souhaite extraire l'ID vidéo de ces URL.

Est-ce que l'API Youtube prend en charge une sorte de fonction où je passe le lien et qui donne l'ID vidéo en retour. Ou dois-je analyser la chaîne moi-même?

J'utilise PHP ... J'apprécierais tous les pointeurs/échantillons de code à cet égard.

Merci

30
Gabriel Spiteri

Voici un exemple de fonction qui utilise une expression régulière pour extraire l'ID youtube d'une URL:

/**
 * get youtube video ID from URL
 *
 * @param string $url
 * @return string Youtube video id or FALSE if none found. 
 */
function youtube_id_from_url($url) {
    $pattern = 
        '%^# Match any youtube URL
        (?:https?://)?  # Optional scheme. Either http or https
        (?:www\.)?      # Optional www subdomain
        (?:             # Group Host alternatives
          youtu\.be/    # Either youtu.be,
        | youtube\.com  # or youtube.com
          (?:           # Group path alternatives
            /embed/     # Either /embed/
          | /v/         # or /v/
          | /watch\?v=  # or /watch\?v=
          )             # End path alternatives.
        )               # End Host alternatives.
        ([\w-]{10,12})  # Allow 10-12 for 11 char youtube id.
        $%x'
        ;
    $result = preg_match($pattern, $url, $matches);
    if ($result) {
        return $matches[1];
    }
    return false;
}

echo youtube_id_from_url('http://youtu.be/NLqAF9hrVbY'); # NLqAF9hrVbY

C'est une adoption de la réponse d'une question similaire .


Ce n'est pas directement l'API que vous recherchez, mais probablement utile. Youtube a un service oembed :

$url = 'http://youtu.be/NLqAF9hrVbY';
var_dump(json_decode(file_get_contents(sprintf('http://www.youtube.com/oembed?url=%s&format=json', urlencode($url)))));

Ce qui fournit plus de méta-informations sur l'URL:

object(stdClass)#1 (13) {
  ["provider_url"]=>
  string(23) "http://www.youtube.com/"
  ["title"]=>
  string(63) "Hang Gliding: 3 Flights in 8 Days at Northside Point of the Mtn"
  ["html"]=>
  string(411) "<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/NLqAF9hrVbY?version=3"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/NLqAF9hrVbY?version=3" type="application/x-shockwave-flash" width="425" height="344" allowscriptaccess="always" allowfullscreen="true"></embed></object>"
  ["author_name"]=>
  string(11) "widgewunner"
  ["height"]=>
  int(344)
  ["thumbnail_width"]=>
  int(480)
  ["width"]=>
  int(425)
  ["version"]=>
  string(3) "1.0"
  ["author_url"]=>
  string(39) "http://www.youtube.com/user/widgewunner"
  ["provider_name"]=>
  string(7) "YouTube"
  ["thumbnail_url"]=>
  string(48) "http://i3.ytimg.com/vi/NLqAF9hrVbY/hqdefault.jpg"
  ["type"]=>
  string(5) "video"
  ["thumbnail_height"]=>
  int(360)
}

Mais l'ID ne fait pas directement partie de la réponse. Cependant, il peut contenir les informations que vous recherchez et il peut être utile de valider l'URL youtube.

79
hakre

J'apporte de légères modifications à l'expression régulière ci-dessus, même si cela fonctionne bien pour l'URL courte youtube (qui a été utilisée dans l'exemple ci-dessus) et l'URL vidéo simple où aucun autre paramètre ne vient après le code vidéo, mais cela ne fonctionne pas pour URL comme http://www.youtube.com/watch?v=B_izAKQ0WqQ&feature=related car le code vidéo n'est pas le dernier paramètre de cette URL. De la même manière, v = {video_code} ne vient pas toujours après la surveillance (alors que l'expression régulière ci-dessus suppose qu'il viendra toujours après la surveillance?), Comme si l'utilisateur a sélectionné la langue OR emplacement à partir de le pied de page, par exemple si l'utilisateur a sélectionné l'anglais (Royaume-Uni) dans l'option Langue, l'URL sera alors http://www.youtube.com/watch?feature=related&hl=en-GB&v=B_izAKQ0WqQ

J'ai donc apporté quelques modifications dans les expressions régulières ci-dessus, mais il faut certainement remercier hakre pour avoir fourni l'expression régulière de base, merci @hakre:

function youtube_id_from_url($url) {
   $pattern =
    '%^# Match any youtube URL
    (?:https?://)?  # Optional scheme. Either http or https
    (?:www\.)?      # Optional www subdomain
    (?:             # Group Host alternatives
      youtu\.be/    # Either youtu.be,
    | youtube\.com  # or youtube.com
      (?:           # Group path alternatives
        /embed/     # Either /embed/
      | /v/         # or /v/
      | .*v=        # or /watch\?v=
      )             # End path alternatives.
    )               # End Host alternatives.
    ([\w-]{10,12})  # Allow 10-12 for 11 char youtube id.
    ($|&).*         # if additional parameters are also in query string after video id.
    $%x'
    ;
    $result = preg_match($pattern, $url, $matches);
    if (false !== $result) {
      return $matches[1];
    }
    return false;
 }
18
Sabeeh Chaudhry

Vous pouvez utiliser la fonction PHP parse_url pour extraire le nom d'hôte, le chemin, la chaîne de requête et le fragment. Vous pouvez ensuite utiliser PHP les fonctions de chaîne pour localiser l'identifiant vidéo.

function getYouTubeVideoId($url)
{
    $video_id = false;
    $url = parse_url($url);
    if (strcasecmp($url['Host'], 'youtu.be') === 0)
    {
        #### (dontcare)://youtu.be/<video id>
        $video_id = substr($url['path'], 1);
    }
    elseif (strcasecmp($url['Host'], 'www.youtube.com') === 0)
    {
        if (isset($url['query']))
        {
            parse_str($url['query'], $url['query']);
            if (isset($url['query']['v']))
            {
                #### (dontcare)://www.youtube.com/(dontcare)?v=<video id>
                $video_id = $url['query']['v'];
            }
        }
        if ($video_id == false)
        {
            $url['path'] = explode('/', substr($url['path'], 1));
            if (in_array($url['path'][0], array('e', 'embed', 'v')))
            {
                #### (dontcare)://www.youtube.com/(whitelist)/<video id>
                $video_id = $url['path'][1];
            }
        }
    }
    return $video_id;
}
$urls = array(
    'http://youtu.be/dQw4w9WgXcQ',
    'http://www.youtube.com/?v=dQw4w9WgXcQ',
    'http://www.youtube.com/?v=dQw4w9WgXcQ&feature=player_embedded',
    'http://www.youtube.com/watch?v=dQw4w9WgXcQ',
    'http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=player_embedded',
    'http://www.youtube.com/v/dQw4w9WgXcQ',
    'http://www.youtube.com/e/dQw4w9WgXcQ',
    'http://www.youtube.com/embed/dQw4w9WgXcQ'
);
foreach ($urls as $url)
{
    echo sprintf('%s -> %s' . PHP_EOL, $url, getYouTubeVideoId($url));
}
10
Salman A

Simple comme return substr (strstr ($ url, 'v ='), 2, 11);

1
dctremblay

Voici une solution simple qui a fonctionné pour moi.

VideoId est le mot le plus long de tous les types d'URL YouTube et il comprend (alphanumérique + "-") avec une longueur minimale de 8 entouré de caractères non Word. Vous pouvez donc rechercher l'expression rationnelle ci-dessous dans l'URL en tant que groupe et ce premier groupe est votre réponse. Premier groupe car certains paramètres youtube tels que enablejsapi ont plus de 8 caractères mais ils viennent toujours après videoId.

Expression régulière: "\ W ([\ w -] {9,}) (\ W | $)"

Voici le code Java Java fonctionnel:

String[] youtubeUrls = {
    "https://www.youtube.com/watch?v=UzRtrjyDwx0",
    "https://youtu.be/6butf1tEVKs?t=22s",
    "https://youtu.be/R46-XgqXkzE?t=2m52s",
    "http://youtu.be/dQw4w9WgXcQ",
    "http://www.youtube.com/?v=dQw4w9WgXcQ",
    "http://www.youtube.com/?v=dQw4w9WgXcQ&feature=player_embedded",
    "http://www.youtube.com/watch?v=dQw4w9WgXcQ",
    "http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=player_embedded",
    "http://www.youtube.com/v/dQw4w9WgXcQ",
    "http://www.youtube.com/e/dQw4w9WgXcQ",
    "http://www.youtube.com/embed/dQw4w9WgXcQ"
};

String pattern = "\\W([\\w-]{9,})(\\W|$)";
Pattern pattern2 = Pattern.compile(pattern);

for (int i=0; i<youtubeUrls.length; i++){
    Matcher matcher2 = pattern2.matcher(youtubeUrls[i]);
    if (matcher2.find()){
        System.out.println(matcher2.group(1));
    }
    else System.out.println("Not found");
}
1
Devinder Singh

Comme mentionné dans un commentaire ci-dessous la réponse valide, nous l'utilisons comme ça, et cela fonctionne très bien!

function youtube_id_from_url($url) {

$url = trim(strtok("$url", '?'));
$url = str_replace("#!/", "", "$url");

    $pattern = 
        '%^# Match any youtube URL
        (?:https?://)?  # Optional scheme. Either http or https
        (?:www\.)?      # Optional www subdomain
        (?:             # Group Host alternatives
          youtu\.be/    # Either youtu.be,
        | youtube\.com  # or youtube.com
          (?:           # Group path alternatives
            /embed/     # Either /embed/
          | /v/         # or /v/
          | /watch\?v=  # or /watch\?v=
          )             # End path alternatives.
        )               # End Host alternatives.
        ([\w-]{10,12})  # Allow 10-12 for 11 char youtube id.
        $%x'
        ;
    $result = preg_match($pattern, $url, $matches);
    if ($result) {
        return $matches[1];
    }
    return false;
}
1
KJS

Je sais que c'est une réponse très tardive mais j'ai trouvé ce fil en recherchant le sujet, donc je veux suggérer une façon plus élégante de le faire en utilisant oEmbed :

echo get_embed('youtube', 'https://www.youtube.com/watch?v=IdxKPCv0bSs');

function get_embed($provider, $url, $max_width = '', $max_height = ''){
    $providers = array(
        'youtube' => 'http://www.youtube.com/oembed'
        /* you can add support for more providers here */
    );

    if(!isset($providers[$provider])){
        return 'Invalid provider!';
    }

    $movie_data_json = @file_get_contents(
        $providers[$provider] . '?url=' . urlencode($url) . 
        "&maxwidth={$max_width}&maxheight={$max_height}&format=json"
    );

    if(!$movie_data_json){
        $error = error_get_last();
        /* remove the PHP stuff from the error and show only the HTTP error message */
        $error_message = preg_replace('/.*: (.*)/', '$1', $error['message']);
        return $error_message;
    }else{
        $movie_data = json_decode($movie_data_json, true);
        return $movie_data['html'];
    }
}

oEmbed permet d'incorporer du contenu provenant de plusieurs sites en ajoutant simplement leur point de terminaison API oEmbed au tableau $ providers dans le code ci-dessus.

1
A. Genedy

Celui-ci, ça va:

function getVideoId() {
    $query = parse_url($this->url, PHP_URL_QUERY);

    $arr = explode('=', $query);

    $index = array_search('v', $arr);

    if ($index !== false) {
        if (isset($arr[$index++])) {
            $string = $arr[$index++];
            if (($amp = strpos($string, '&')) !== false) {
                return substr($string, 0, $amp);
            } else {
                return $string;
            }
        } else {
            return false;
        }
    }
    return false;
}

Pas d'expression régulière, prend en charge plusieurs paramètres de requête, c'est-à-dire https://www.youtube.com/watch?v=PEQxWg92Ux4&index=9&list=RDMMom0RGEnWIEk fonctionne également.

0
petwho