END; // This code will execute if the user entered a search query in the form // and submitted the form. Otherwise, the page displays the form above. if (isset($_GET['q'])) { /* * Set $DEVELOPER_KEY to the "API key" value from the "Access" tab of the * {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}> * Please ensure that you have enabled the YouTube Data API for your project. */ $DEVELOPER_KEY = 'AIzaSyBnd8Wmi71lLjlIcJXD8XRknXAMRxISLOs'; $client = new Google_Client(); $client->setDeveloperKey($DEVELOPER_KEY); // Define an object that will be used to make all API requests. $youtube = new Google_Service_YouTube($client); $htmlBody = ''; $videoResults = array(); $query = $_GET['q']; try { // Call the search.list method to retrieve results matching the specified // query term. $searchResponse = $youtube->search->listSearch('snippet', array('maxResults' => 20, 'q' => $_GET['q'], 'type'=>'video', 'order'=>'date')); $videos = ''; // Add each result to the appropriate list, and then display the lists of // matching videos. // По сути должен быть только один вызов foreach по listSearch получаем $массив ID новых видео объединяем в строку push(',',$массив) передаем строку в listVideos затем его сортируем foreach ($searchResponse['items'] as $searchResult) { $response = $youtube->videos->listVideos("snippet,statistics", array('id' => $searchResult['id']['videoId'])); foreach ($response['items'] as $searchId) { !(empty($searchId['statistics']['viewCount'])) or $searchId['statistics']['viewCount']='0'; $videoResults[]=$searchId; } } uasort($videoResults, function ($a, $b) { if ($a['statistics']['viewCount'] == $b['statistics']['viewCount']) { return 0; } return ($a['statistics']['viewCount'] < $b['statistics']['viewCount']) ? 1 : -1; }); foreach ($videoResults as $lastResult) { $datePublishedAt=str_replace(["T",".000Z"], " ", $lastResult['snippet']['publishedAt']); $videos .= sprintf("
  • Название: %s
    Автор: %s
    Дата публикации: %s
    Количество просмотров: %s
  • ", $lastResult['snippet']['title'], $lastResult['snippet']['channelTitle'],$datePublishedAt,$lastResult['statistics']['viewCount'],$lastResult['id']); } $htmlBody .="

    Результат поиска по запросу: $query

      $videos
    "; } catch (Google_Service_Exception $e) { $htmlBody .= sprintf('

    Произошла ошибка службы: %s

    ', htmlspecialchars($e->getMessage())); } catch (Google_Exception $e) { $htmlBody .= sprintf('

    Произошла ошибка клиента: %s

    ', htmlspecialchars($e->getMessage())); } } ?> YouTube Search