{"id":7176,"date":"2023-07-22T09:21:14","date_gmt":"2023-07-22T13:21:14","guid":{"rendered":"https:\/\/themespress.ca\/?p=7176"},"modified":"2023-07-22T09:21:14","modified_gmt":"2023-07-22T13:21:14","slug":"class-php-api-you-tube-version-3","status":"publish","type":"post","link":"https:\/\/themespress.ca\/en\/class-php-api-you-tube-version-3\/","title":{"rendered":"Class PHP &#8211; API You Tube &#8211; Version 3"},"content":{"rendered":"<div class=\"wpb-content-wrapper\"><div class=\"vc_row wpb_row vc_row-fluid\"><div class=\"wpb_column vc_column_container vc_col-sm-12\"><div class=\"vc_column-inner\"><div class=\"wpb_wrapper\">\n\t<div class=\"wpb_text_column wpb_content_element\" >\n\t\t<div class=\"wpb_wrapper\">\n\t\t\t<p>We have created a basic PHP class that will let you connect to YouTube&#8217;s API and display a video or a channel based on its ID and matching data.<\/p>\n<h3>Here are the video&#8217;s data available:<\/h3>\n<ul>\n<li>Title<\/li>\n<li>Description<\/li>\n<li>Thumbnail<\/li>\n<li>Views<\/li>\n<li>Likes<\/li>\n<li>Dislikes<\/li>\n<li>Comments<\/li>\n<li>Date Published<\/li>\n<li>Channel Title<\/li>\n<li>Tags<\/li>\n<li>Default Language<\/li>\n<\/ul>\n\n\t\t<\/div>\n\t<\/div>\n<h2 style=\"text-align: left\" class=\"vc_custom_heading vc_do_custom_heading\" >Class PHP - API You Tube<\/h2><div id=\"ts-enlighterjs-container-3382051\" class=\"ts-enlighterjs-container-single-enabled  \" style=\"width: 100%;  margin-top: 0px; margin-bottom: 0px;\" data-enlighter-doubleclick=\"true\" data-enlighter-windowbutton=\"true\" data-enlighter-windowtext=\"New Window\" data-enlighter-rawbutton=\"true\" data-enlighter-rawtext=\"RAW Code\" data-enlighter-infobutton=\"false\" data-enlighter-infotext=\"EnlighterJS\" data-enlighter-indent=\"2\"><pre id=\"ts-enlighterjs-pre-3382051\" class=\"\" style=\"white-space: pre-wrap; height: 100%; margin: 0; padding: 0;\" data-enlighter-language=\"standard\" data-enlighter-theme=\"enlighter\" data-enlighter-group=\"\" data-enlighter-title=\"\" data-enlighter-linenumbers=\"true\" data-enlighter-lineoffset=\"1\" data-enlighter-highlight=\"\">\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Requires and includes admin theme  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass WPVYouTubeAPI {\n    private $apiKey;\n\n    public function __construct($apiKey)\n    {\n       $this-&gt;apiKey = $apiKey;\n    }\n\n    \/**\n     * Retrieves videos by channel ID.\n     * @param string $channelId The ID of the channel.\n     * @param int $maxResults The maximum number of videos to retrieve.\n     * @return array An array containing the channel name and videos.\n     *\/\n    public function wpvgetVideosByChannel($channelId, $maxResults = 10) {\n        $url = &quot;https:\/\/www.googleapis.com\/youtube\/v3\/search?part=snippet&amp;channelId={$channelId}&amp;maxResults={$maxResults}&amp;key={$this-&gt;apiKey}&quot;;\n        $response = $this-&gt;wpvsendRequest($url);\n        $videos = array();\n        foreach ($response[&#039;items&#039;] as $item) {\n            $videoId = $item[&#039;id&#039;][&#039;videoId&#039;];\n            $video = $this-&gt;getVideoDetails($videoId);\n            $videos[] = $video;\n        }\n        \/\/ Retrieve the channel name from the first item in the response\n        $channelName = $response[&#039;items&#039;][0][&#039;snippet&#039;][&#039;channelTitle&#039;];\n        return array(\n            &#039;channelName&#039; =&gt; $channelName,\n            &#039;videos&#039; =&gt; $videos\n        );\n    }\n    \n    \/**\n     * Retrieves video details by video ID.\n     * @param string $videoId The ID of the video.\n     * @return array An array containing the video details.\n     *\/\n    public function wpvgetVideoDetails($videoId)\n    {\n        $url = &quot;https:\/\/www.googleapis.com\/youtube\/v3\/videos?part=snippet,statistics&amp;id={$videoId}&amp;key={$this-&gt;apiKey}&quot;;\n\n        $response = $this-&gt;wpvsendRequest($url);\n\n        $video = array(\n            &#039;title&#039; =&gt; $response[&#039;items&#039;][0][&#039;snippet&#039;][&#039;title&#039;],\n            &#039;description&#039; =&gt; $response[&#039;items&#039;][0][&#039;snippet&#039;][&#039;description&#039;],\n            &#039;thumbnail&#039; =&gt; $response[&#039;items&#039;][0][&#039;snippet&#039;][&#039;thumbnails&#039;][&#039;default&#039;][&#039;url&#039;],\n            &#039;views&#039; =&gt; $response[&#039;items&#039;][0][&#039;statistics&#039;][&#039;viewCount&#039;],\n            &#039;likes&#039; =&gt; $response[&#039;items&#039;][0][&#039;statistics&#039;][&#039;likeCount&#039;],\n            &#039;dislikes&#039; =&gt; $response[&#039;items&#039;][0][&#039;statistics&#039;][&#039;dislikeCount&#039;],\n            &#039;comments&#039; =&gt; $response[&#039;items&#039;][0][&#039;statistics&#039;][&#039;commentCount&#039;],\n            &#039;publishedAt&#039; =&gt; $response[&#039;items&#039;][0][&#039;snippet&#039;][&#039;publishedAt&#039;],\n            &#039;duration&#039; =&gt; $response[&#039;items&#039;][0][&#039;contentDetails&#039;][&#039;duration&#039;],\n            &#039;channelTitle&#039; =&gt; $response[&#039;items&#039;][0][&#039;snippet&#039;][&#039;channelTitle&#039;],\n            &#039;tags&#039; =&gt; $response[&#039;items&#039;][0][&#039;snippet&#039;][&#039;tags&#039;],\n            &#039;categoryId&#039; =&gt; $response[&#039;items&#039;][0][&#039;snippet&#039;][&#039;categoryId&#039;],\n            &#039;defaultLanguage&#039; =&gt; $response[&#039;items&#039;][0][&#039;snippet&#039;][&#039;defaultLanguage&#039;],\n            &#039;liveBroadcastContent&#039; =&gt; $response[&#039;items&#039;][0][&#039;snippet&#039;][&#039;liveBroadcastContent&#039;],\n            &#039;license&#039; =&gt; $response[&#039;items&#039;][0][&#039;status&#039;][&#039;license&#039;],\n            &#039;embedHtml&#039; =&gt; $response[&#039;items&#039;][0][&#039;player&#039;][&#039;embedHtml&#039;],\n            &#039;allowedRegions&#039; =&gt; $response[&#039;items&#039;][0][&#039;contentDetails&#039;][&#039;regionRestriction&#039;][&#039;allowed&#039;],\n            &#039;blockedRegions&#039; =&gt; $response[&#039;items&#039;][0][&#039;contentDetails&#039;][&#039;regionRestriction&#039;][&#039;blocked&#039;],\n            \/\/ Add any other data you want to retrieve\n        );\n\n        return $video;\n    }\n\n    \/**\n     * Sends a request to the specified URL using cURL.\n     * @param string $url The URL to send the request to.\n     * @return array The JSON response as an associative array.\n     * @throws Exception If cURL encounters an error.\n     *\/\n    private function wpvsendRequest($url)\n    {\n        $curl = curl_init();\n\n        curl_setopt_array($curl, array(\n            CURLOPT_URL =&gt; $url,\n            CURLOPT_RETURNTRANSFER =&gt; true,\n            CURLOPT_FOLLOWLOCATION =&gt; true,\n            CURLOPT_ENCODING =&gt; &quot;&quot;,\n            CURLOPT_TIMEOUT =&gt; 30,\n            CURLOPT_HTTP_VERSION =&gt; CURL_HTTP_VERSION_1_1,\n            CURLOPT_CUSTOMREQUEST =&gt; &quot;GET&quot;,\n        ));\n\n        $response = curl_exec($curl);\n        $err = curl_error($curl);\n\n        curl_close($curl);\n\n        if ($err) {\n            throw new Exception(&quot;cURL Error #:&quot; . $err);\n        }\n        return json_decode($response, true);\n    }\n    \n    \/**\n     * Retrieves the comments of a video by its video ID.\n     * @param string $videoId The ID of the video.\n     * @return array An array containing the video comments.\n     *\/\n    public function wpvgetVideoComments($videoId) {\n        $url = &#039;https:\/\/www.googleapis.com\/youtube\/v3\/commentThreads?videoId=&#039; . $videoId . &#039;&amp;part=snippet&amp;maxResults=10&amp;key=&#039; . $this-&gt;apiKey;\n        $response = $this-&gt;wpvsendRequest($url);\n        \n        $comments = array();\n        \n        if (isset($response[&#039;items&#039;])) {\n            foreach ($response[&#039;items&#039;] as $item) {\n                $comment = $item[&#039;snippet&#039;][&#039;topLevelComment&#039;][&#039;snippet&#039;][&#039;textDisplay&#039;];\n                $comments[] = $comment;\n            }\n        }\n        \n        return $comments;\n    }\n    \n    \/**\n     * Retrieves the channel ID from a video by its video ID.\n     * @param string $videoId The ID of the video.\n     * @return string|null The channel ID, or null if not found.\n     *\/\n    public function wpvgetChannelIdFromVideo($videoId){\n        $url = &quot;https:\/\/www.googleapis.com\/youtube\/v3\/videos?part=snippet&amp;id={$videoId}&amp;key={$this-&gt;apiKey}&quot;;\n        $response = $this-&gt;wpvsendRequest($url);\n        if (!empty($response[&#039;items&#039;])) {\n            $channelId = $response[&#039;items&#039;][0][&#039;snippet&#039;][&#039;channelId&#039;];\n            return $channelId;\n        }\n        return null;\n    }\n    \n    \/**\n     * Formats the number of views to a human-readable format.\n     * @param int $views The number of views.\n     * @return string The formatted views.\n     *\/\n    public function wpvformatViews($views) {\n        if ($views &gt;= 1000000000) {\n            return round($views \/ 1000000000, 1) . &#039; billion&#039;;\n        } elseif ($views &gt;= 1000000) {\n            return round($views \/ 1000000, 1) . &#039; million&#039;;\n        } elseif ($views &gt;= 1000) {\n            return round($views \/ 1000, 1) . &#039; thousand&#039;;\n        } else {\n            return $views;\n        }\n    }\n   \n}<\/pre><\/div>\n\t<div class=\"wpb_text_column wpb_content_element\" >\n\t\t<div class=\"wpb_wrapper\">\n\t\t\t<p>We will now call the PHP class and display the data. You need to update your <strong>API key in the $apiKey variable<\/strong> and then make call dynamically <strong>your video&#8217;s ID in the $videoId variable.<\/strong><\/p>\n\n\t\t<\/div>\n\t<\/div>\n<div id=\"ts-enlighterjs-container-5375428\" class=\"ts-enlighterjs-container-single-enabled  \" style=\"width: 100%;  margin-top: 0px; margin-bottom: 0px;\" data-enlighter-doubleclick=\"true\" data-enlighter-windowbutton=\"true\" data-enlighter-windowtext=\"New Window\" data-enlighter-rawbutton=\"true\" data-enlighter-rawtext=\"RAW Code\" data-enlighter-infobutton=\"false\" data-enlighter-infotext=\"EnlighterJS\" data-enlighter-indent=\"2\"><pre id=\"ts-enlighterjs-pre-5375428\" class=\"\" style=\"white-space: pre-wrap; height: 100%; margin: 0; padding: 0;\" data-enlighter-language=\"standard\" data-enlighter-theme=\"enlighter\" data-enlighter-group=\"\" data-enlighter-title=\"\" data-enlighter-linenumbers=\"true\" data-enlighter-lineoffset=\"1\" data-enlighter-highlight=\"\">\/\/ API Call Class PHP\n$apiKey = &#039;YOUR API KEY HERE&#039;;\n$youtube = new WPVYouTubeAPI($apiKey);\n$videoId = &#039;YOUR VIDEO ID HERE&#039;;\n\n\/\/ Get video details\n$videoDetails = $youtube-&gt;wpvgetVideoDetails($videoId);\n$channelId = $youtube-&gt;wpvgetChannelIdFromVideo($videoId);\n$publishedDate = date(&#039;Y-m-d&#039;, strtotime($videoDetails[&#039;publishedAt&#039;]));\n\n\/\/ Echo the title of the video\necho &#039;Titre : &#039; . $videoDetails[&#039;title&#039;] . &#039;&lt;br&gt;&#039;;\n\n\/\/echo &#039;Description : &#039; . $videoDetails[&#039;description&#039;] . &#039;&lt;br&gt;&#039;;\necho &#039;&lt;img src=&quot;&#039; . $videoDetails[&#039;thumbnail&#039;] . &#039;&quot; alt=&quot;Thumbnail de la vid&eacute;o&quot;&gt;&lt;br&gt;&#039;;\n\n\/\/ Display the formatted duration\n\/\/echo &#039;Dur&eacute;e : &#039; . $formattedDuration . &#039;&lt;br&gt;&#039;;\n\n\/\/ Echo the channel title\necho &#039;Channel : &#039; . $videoDetails[&#039;channelTitle&#039;] . &#039;&lt;br&gt;&#039;;\n\n\/\/ Echo the published date of the video\necho &#039;Publi&eacute; le : &#039; . $publishedDate . &#039;&lt;br&gt;&#039;;\n\n\/\/ Check if default language is available\nif (!empty($videoDetails[&#039;defaultLanguage&#039;])) {\n    echo &#039;Language : &#039; . $videoDetails[&#039;defaultLanguage&#039;] . &#039;&lt;br&gt;&#039;;\n} else {\n    echo &#039;Language : Undefined&lt;br&gt;&#039;;\n}\n\n\/\/ Display license\nif (!empty($videoDetails[&#039;license&#039;])) {\n    echo &#039;License : &#039; . $videoDetails[&#039;license&#039;] . &#039;&lt;br&gt;&#039;;\n} else {\n    echo &#039;License : Not specified&lt;br&gt;&#039;;\n}\n\n\/\/ Display the Channel Name of the video \nif (!empty($videoDetails[&#039;channelId&#039;])) {\n    $maxResults = 10; \/\/ Maximum number of videos to retrieve\n    $videosData = $youtube-&gt;wpvgetVideosByChannel($channelId, $maxResults);\n    $channelName = $videosData[&#039;channelName&#039;];\n    $videos = $videosData[&#039;videos&#039;];\n    echo &quot;Channel Name: $channelName&lt;br&gt;&quot;;\n} else {\n    echo &quot;No channel found for the video.&lt;br&gt;&quot;;\n}\n\n\/\/ Display the tags\nif (isset($videoDetails[&#039;tags&#039;])) {\n    if (is_array($videoDetails[&#039;tags&#039;])) {\n        $formattedTags = array_map(&#039;ucfirst&#039;, $videoDetails[&#039;tags&#039;]); \/\/ Apply ucfirst to each tag\n        $tags = implode(&#039;, &#039;, $formattedTags);\n        echo &#039;Tags: &#039; . $tags . &#039;&lt;br&gt;&#039;;\n    } else {\n        $tags = ucfirst($videoDetails[&#039;tags&#039;]); \/\/ Capitalize the first letter\n        echo &#039;Mots-cl&eacute;s : &#039; . $tags . &#039;&lt;br&gt;&#039;;\n    }\n} else {\n    echo &#039;Mots-cl&eacute;s : None&lt;br&gt;&#039;;\n}\n\n\/\/ Display the Views of the video \necho &#039;Vues : &#039; . $youtube-&gt;wpvformatViews($videoDetails[&#039;views&#039;]) . &#039;&lt;br&gt;&#039;;\n\n\/\/ Display the Likes of the video \necho &#039;Passion&eacute;(e)s : &#039; . $videoDetails[&#039;likes&#039;] . &#039;&lt;br&gt;&#039;;\n\n\/\/ Display the Dislikes of the video \n$dislikes = $videoDetails[&#039;dislikes&#039;];\nif ($dislikes &gt; 0) {\n    echo &#039;Dislikes : &#039; . $dislikes . &#039;&lt;br&gt;&#039;;\n} else {\n    echo &#039;Dislikes : 0&lt;br&gt;&#039;;\n}\n\n\/\/ Display the Favorites of the video \n$favorites = $videoDetails[&#039;favorites&#039;];\nif ($favorites &gt; 0) {\n    echo &#039;Favorites : &#039; . $favorites . &#039;&lt;br&gt;&#039;;\n} else {\n    echo &#039;Favorites : 0&lt;br&gt;&#039;;\n}\n\n\/\/ Display the Comments of the video \necho &#039;Comments : &#039; . $videoDetails[&#039;comments&#039;] . &#039;&lt;br&gt;&#039;;<\/pre><\/div>\n\t<div class=\"wpb_text_column wpb_content_element\" >\n\t\t<div class=\"wpb_wrapper\">\n\t\t\t<p>You can also include <strong><a href=\"https:\/\/fontawesome.com\/v5\/search\" target=\"_blank\" rel=\"noopener\">Font Awesome Version 5<\/a><\/strong> icons by creating an <a href=\"https:\/\/gist.github.com\/danielmcclure\/d1b8e492bedcced7c8016ed37f197623\" target=\"_blank\" rel=\"noopener\"><strong>enqueue script<\/strong><\/a> or <strong>add it in the Class PHP WPVYouTubeAPI class<\/strong>.<\/p>\n\n\t\t<\/div>\n\t<\/div>\n<div id=\"ts-enlighterjs-container-7780048\" class=\"ts-enlighterjs-container-single-enabled  \" style=\"width: 100%;  margin-top: 0px; margin-bottom: 0px;\" data-enlighter-doubleclick=\"true\" data-enlighter-windowbutton=\"true\" data-enlighter-windowtext=\"New Window\" data-enlighter-rawbutton=\"true\" data-enlighter-rawtext=\"RAW Code\" data-enlighter-infobutton=\"false\" data-enlighter-infotext=\"EnlighterJS\" data-enlighter-indent=\"2\"><pre id=\"ts-enlighterjs-pre-7780048\" class=\"\" style=\"white-space: pre-wrap; height: 100%; margin: 0; padding: 0;\" data-enlighter-language=\"standard\" data-enlighter-theme=\"enlighter\" data-enlighter-group=\"\" data-enlighter-title=\"\" data-enlighter-linenumbers=\"true\" data-enlighter-lineoffset=\"1\" data-enlighter-highlight=\"\">\/\/ Enqueue Font Awesome 5 in WordPress \nfunction themespress_load_font_awesome() {\n    \/\/ You can find the current URL for the latest version here: https:\/\/fontawesome.com\/start\n    wp_enqueue_style( &#039;font-awesome-free&#039;, &#039;\/\/use.fontawesome.com\/releases\/v5.6.3\/css\/all.css&#039; );\n}\nadd_action( &#039;wp_enqueue_scripts&#039;, &#039;themespress_load_font_awesome&#039; );<\/pre><\/div><\/div><\/div><\/div><\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"We have created a basic PHP class that will let you connect to YouTube's API and display a video or a channel based on its ID and matching data. Here<div class=\"read-more\"><a class=\"btn button-secondary\" href=\"https:\/\/themespress.ca\/en\/class-php-api-you-tube-version-3\/\">Read More<\/a><\/div>","protected":false},"author":81,"featured_media":7148,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[283],"tags":[],"class_list":["post-7176","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-tutorials"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/themespress.ca\/en\/wp-json\/wp\/v2\/posts\/7176","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/themespress.ca\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/themespress.ca\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/themespress.ca\/en\/wp-json\/wp\/v2\/users\/81"}],"replies":[{"embeddable":true,"href":"https:\/\/themespress.ca\/en\/wp-json\/wp\/v2\/comments?post=7176"}],"version-history":[{"count":0,"href":"https:\/\/themespress.ca\/en\/wp-json\/wp\/v2\/posts\/7176\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/themespress.ca\/en\/wp-json\/wp\/v2\/media\/7148"}],"wp:attachment":[{"href":"https:\/\/themespress.ca\/en\/wp-json\/wp\/v2\/media?parent=7176"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/themespress.ca\/en\/wp-json\/wp\/v2\/categories?post=7176"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/themespress.ca\/en\/wp-json\/wp\/v2\/tags?post=7176"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}