如何在 PHP 中嵌入 YouTube 视频?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/412467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:40:17  来源:igfitidea点击:

How to embed YouTube videos in PHP?

phphtmlvideoyoutubeyoutube-api

提问by Satish Ravipati

Can anyone give me an idea how can we showor embed a YouTube video if we just have the URL or the Embed code?

如果我们只有 URL 或嵌入代码,谁能告诉我如何显示或嵌入 YouTube 视频?

回答by Alec Smart

You have to ask users to store the 11 character code from the youtube video.

您必须要求用户存储 youtube 视频中的 11 个字符代码。

For e.g. http://www.youtube.com/watch?v=Ahg6qcgoay4

例如http://www.youtube.com/watch?v=Ahg6qcgoay4

The eleven character code is : Ahg6qcgoay4

十一字代码为:Ahg6qcgoay4

You then take this code and place it in your database. Then wherever you want to place the youtube video in your page, load the character from the database and put the following code:-

然后,您获取此代码并将其放入您的数据库中。然后,无论您想将 YouTube 视频放置在页面中的哪个位置,从数据库加载角色并输入以下代码:-

e.g. for Ahg6qcgoay4 it will be :

例如,对于 Ahg6qcgoay4,它将是:

<object width="425" height="350" data="http://www.youtube.com/v/Ahg6qcgoay4" type="application/x-shockwave-flash"><param name="src" value="http://www.youtube.com/v/Ahg6qcgoay4" /></object>

回答by Salman A

Do not store the embed code in your database -- YouTube may change the embed code and URL parameters from time to time. For example the <object>embed code has been retired in favor of <iframe>embed code. You should parse out the video id from the URL/embed code (using regular expressions, URL parsing functions or HTML parser) and store it. Then display it using whatever mechanism currently offered by YouTube API.

不要将嵌入代码存储在您的数据库中——YouTube 可能会不时更改嵌入代码和 URL 参数。例如,<object>嵌入代码已被淘汰,取而代之的是<iframe>嵌入代码。您应该从 URL/嵌入代码中解析出视频 ID(使用正则表达式、URL 解析函数或 HTML 解析器)并存储它。然后使用 YouTube API 当前提供的任何机制显示它。

A naive PHP example for extracting the video id is as follows:

一个用于提取视频 ID 的简单 PHP 示例如下:

<?php
    preg_match(
        '/[\?\&]v=([^\?\&]+)/',
        'http://www.youtube.com/watch?v=OzHvVoUGTOM&feature=channel',
        $matches
    );
    // $matches[1] should contain the youtube id
?>

I suggest that you look at these articles to figure out what to do with these ids:

我建议您查看这些文章以弄清楚如何处理这些 id:

To create your own YouTube video player:

要创建您自己的 YouTube 视频播放器:

回答by fanky

From both long and short youtube urls you can get the embed this way:

从长和短的 youtube 网址,您都可以通过以下方式获得嵌入:

$ytarray=explode("/", $videolink);
$ytendstring=end($ytarray);
$ytendarray=explode("?v=", $ytendstring);
$ytendstring=end($ytendarray);
$ytendarray=explode("&", $ytendstring);
$ytcode=$ytendarray[0];
echo "<iframe width=\"420\" height=\"315\" src=\"http://www.youtube.com/embed/$ytcode\" frameborder=\"0\" allowfullscreen></iframe>";

Hope it helps someone

希望它可以帮助某人

回答by KAD

The <object>and <embed>tags are deprecated as per HTML Youtube Videos, it is preferable to use the <iframe>tag to do so.

<object><embed>标签不赞成每个HTML YouTube视频,最好使用<iframe>标签来做到这一点。

<iframe width="420" height="315"
src="http://www.youtube.com/embed/XGSy3_Czz8k?autoplay=1">
</iframe>

In order for your users not spend their entire lifetime trying to find the video id in links to put it in your form field, let them post the link of the video they find on youtube and you can use the following regex to obtain the video id:

为了让您的用户一生不会在链接中查找视频 ID 以将其放入表单字段,请让他们发布他们在 youtube 上找到的视频的链接,您可以使用以下正则表达式获取视频 ID :

preg_match("/^(?:http(?:s)?:\/\/)?
    (?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|
    (?:embed|v|vi|user)\/))([^\?&\"'>]+)/", $url, $matches);

To get the video id you can fetch it $matches[1], these will match:

要获取您可以获取的视频 ID $matches[1],它们将匹配:

Part of this answer is referred by @shawn's answer in this question.

@shawn 在这个问题中的回答引用了这个答案的一部分。

回答by hasen

Use a regex to extract the "video id" after watch?v=

使用正则表达式提取“视频ID”之后 watch?v=

Store the video id in a variable, let's call this variable vid

将视频 id 存储在一个变量中,让我们调用这个变量 vid

Get the embed code from a random video, remove the video id from the embed code and replace it with the vidyou got.

从随机视频中获取嵌入代码,从嵌入代码中删除视频 ID 并将其替换为vid您获得的。

I don't know how to deal with regex in php, but it shouldn't be too hard

我不知道如何处理 php 中的正则表达式,但应该不会太难

Here's example code in python:

这是python中的示例代码:

>>> ytlink = 'http://www.youtube.com/watch?v=7-dXUEbBz70'
>>> import re
>>> vid = re.findall( r'v\=([\-\w]+)', ytlink )[0]
>>> vid
'7-dXUEbBz70'
>>> print '''<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/%s&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/%s&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>''' % (vid,vid)
<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/7-dXUEbBz70&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/7-dXUEbBz70&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>
>>>

The regular expression v\=([\-\w]+)captures a (sub)string of characters and dashes that comes after v=

正则表达式v\=([\-\w]+)捕获后面的字符和破折号的(子)字符串v=

回答by Ross

Here is some code I've wrote to automatically turn URL's into links and automatically embed any video urls from youtube. I made it for a chat room I'm working on and it works pretty well. I'm sure it will work just fine for any other purpose as well like a blog for instance.

这是我编写的一些代码,用于自动将 URL 转换为链接并自动嵌入来自 youtube 的任何视频 URL。我为我正在工作的聊天室制作了它,并且效果很好。我相信它可以很好地用于任何其他目的,例如博客。

All you have to do is call the function "autolink()" and pass it the string to be parsed.

您所要做的就是调用函数“autolink()”并将要解析的字符串传递给它。

For example include the function below and then echo this code.

例如,包含下面的函数,然后回显此代码。

`
echo '<div id="chat_message">'.autolink($string).'</div>';

/****************Function to include****************/

<?php

function autolink($string){
    // force http: on www.
    $string = str_ireplace( "www.", "http://www.", $string );
    // eliminate duplicates after force
    $string = str_ireplace( "http://http://www.", "http://www.", $string );
    $string = str_ireplace( "https://http://www.", "https://www.", $string );

    // The Regular Expression filter
    $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    // Check if there is a url in the text

$m = preg_match_all($reg_exUrl, $string, $match); 

if ($m) { 
$links=$match[0]; 
for ($j=0;$j<$m;$j++) { 

    if(substr($links[$j], 0, 18) == 'http://www.youtube'){

    $string=str_replace($links[$j],'<a href="'.$links[$j].'" rel="nofollow" target="_blank">'.$links[$j].'</a>',$string).'<br /><iframe title="YouTube video player" class="youtube-player" type="text/html" width="320" height="185" src="http://www.youtube.com/embed/'.substr($links[$j], -11).'" frameborder="0" allowFullScreen></iframe><br />';


    }else{

    $string=str_replace($links[$j],'<a href="'.$links[$j].'" rel="nofollow" target="_blank">'.$links[$j].'</a>',$string);

        } 

    } 
} 




               return ($string);
 }

?>

`

`

回答by CMS

If you want to upload videos programatically, check the YouTube Data APIfor PHP

如果您想以编程方式上传视频,请查看YouTube Data APIfor PHP

回答by akfaisel

You can do this simple with Joomla. Let me assume a sample YouTube URL - https://www.youtube.com/watch?v=ndmXkyohT1M

你可以用 Joomla 做到这一点。让我假设一个示例 YouTube URL - https://www.youtube.com/watch?v=ndmXkyohT1M

<?php 
$youtubeUrl =  JUri::getInstance('https://www.youtube.com/watch?v=ndmXkyohT1M');
$videoId = $youtubeUrl->getVar('v'); ?>

<iframe id="ytplayer" type="text/html" width="640" height="390"  src="http://www.youtube.com/embed/<?php echo $videoId; ?>"  frameborder="0"/>

回答by OscarRyz

Searching for this same topic I found another method using Javascript an Youtube API's

搜索相同的主题,我发现了另一种使用 Javascript 和 Youtube API 的方法

Directly from: http://code.google.com/apis/ajax/playground/#simple_embed

直接来自:http: //code.google.com/apis/ajax/playground/#simple_embed

Loading the API

加载 API

<script src="http://www.google.com/jsapi" type="text/javascript"></script>

And executing the following javascript code:

并执行以下 javascript 代码:

  google.load("swfobject", "2.1");
  function _run() {

    var videoID = "ylLzyHk54Z0"
    var params = { allowScriptAccess: "always" };
    var atts = { id: "ytPlayer" };
    // All of the magic handled by SWFObject (http://code.google.com/p/swfobject/)
    swfobject.embedSWF("http://www.youtube.com/v/" + videoID + "&enablejsapi=1&playerapiid=player1",
                       "videoDiv", "480", "295", "8", null, null, params, atts);


  }
  google.setOnLoadCallback(_run);

The complete sample is in the previously referred page http://code.google.com/apis/ajax/playground

完整的示例位于之前提到的页面http://code.google.com/apis/ajax/playground

回答by OscarRyz

You can simply create a php input form for Varchar date,give it a varcharlength of lets say 300. Then ask the users to copy and paste the Embed code.When you view the records, you will view the streamed video.

您可以简单地创建一个 php 输入表单Varchar date,让它的varchar长度为 300。然后要求用户复制并粘贴嵌入代码。当您查看记录时,您将查看流式视频。