<?php
function getYouTubeVideoId($query) {
    $query = urlencode($query);
    $ch = curl_init("https://www.youtube.com/results?search_query=$query");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3');
    $result = curl_exec($ch);
    curl_close($ch);

    if (preg_match('/"videoId":"(.*?)"/', $result, $matches)) {
        return $matches[1];
    }
    return null;
}

$artista = "Reik";
$cancion = "Ya me entere";
$query = "$artista $cancion";

$videoId = getYouTubeVideoId($query);

if ($videoId) {
    echo '<h3>' . htmlspecialchars($cancion) . ' - ' . htmlspecialchars($artista) . '</h3>';
    echo '<iframe width="350" height="300" src="https://www.youtube.com/embed/' . $videoId . '?start=5&autoplay=1&loop=1&playlist=' . $videoId . '&rel=0&modestbranding=1&showinfo=0&iv_load_policy=3&disablekb=1" frameborder="0" allowfullscreen></iframe>';
} else {
    echo 'No se encontró el video para "' . htmlspecialchars($query) . '".';
}
?>
