允许将视频嵌入到评论/文本中

时间:2010-12-05 00:08:53

标签: php video youtube

wordpress如何让你只通过网址嵌入youtube / dailymotion / vimeo视频?例如,如果您输入[youtube = http://www.youtube.com/watch?v = cXXm696UbKY],视频将显示在那里。 无论如何使用markdown在php中安全地执行此操作吗?

2 个答案:

答案 0 :(得分:2)

此视频平台中的大多数(全部?)都提供了oEmbed支持。

例如,对于YouTube视频http://www.youtube.com/watch?v=cXXm696UbKY,它是http://www.youtube.com/oembed?url=http%3A//www.youtube.com/watch%3Fv%cXXm696UbKY

这将返回一个响应,您可以使用json_decode轻松解析。

{
    "provider_url": "http:\/\/www.youtube.com\/",
    "title": "Auto-Tune the News #8: dragons. geese. Michael Vick. (ft. T-Pain)",
    "html": "<object width=\"425\" height=\"344\"><param name=\"movie\" value=\"http:\/\/www.youtube.com\/v\/bDOYN-6gdRE?fs=1\"><\/param><param name=\"allowFullScreen\" value=\"true\"><\/param><param name=\"allowscriptaccess\" value=\"always\"><\/param><embed src=\"http:\/\/www.youtube.com\/v\/bDOYN-6gdRE?fs=1\" type=\"application\/x-shockwave-flash\" width=\"425\" height=\"344\" allowscriptaccess=\"always\" allowfullscreen=\"true\"><\/embed><\/object>",
    "author_name": "schmoyoho",
    "height": 344,
    "thumbnail_width": 480,
    "width": 425,
    "version": "1.0",
    "author_url": "http:\/\/www.youtube.com\/user\/schmoyoho",
    "provider_name": "YouTube",
    "thumbnail_url": "http:\/\/i3.ytimg.com\/vi\/bDOYN-6gdRE\/hqdefault.jpg",
    "type": "video",
    "thumbnail_height": 360
}

有趣的部分是html属性。

因此我们所要做的就是在文本中搜索[YouTube=...]代码,提取YouTube网址并通过oEmbed检索嵌入代码。

这是一个工作示例:

<?php
function getYouTubeCode($url)
{
    $oembedUrl = 'http://www.youtube.com/oembed?url=' . urlencode($url);

    // The @-operator suppresses errors if the YouTube oEmbed service can't handle our request
    $data = @file_get_contents($oembedUrl);

    // If $data contains invalid JSON code, it will return null
    $data = json_decode($data);

    // So if $data is not an object now, we abort
    if (!is_object($data)) {
        return '';
    }

    // Otherwise we return the YouTube embed code
    return $data->html;
}

$text = '<h1>Hi There</h1><p>You gotta watch this video:</p><p>[YouTube=http://www.youtube.com/watch?v=cXXm696UbKY]</p>';

$matches = array();

// We scan the $text variable for all occurrences of "[YouTube=<Any character except right squared bracket>]"
if (preg_match_all('/\[YouTube=([^\]]+)\]/i', $text, $matches, PREG_SET_ORDER)) {
    foreach ($matches as $match) {
        // Eg. $match[0] is "[YouTube=http://www.youtube.com/watch?v=cXXm696UbKY]"
        // and $match[1] is "http://www.youtube.com/watch?v=cXXm696UbKY"
        $text = str_replace($match[0], getYouTubeCode($match[1]), $text);
    }
}

echo $text;

答案 1 :(得分:1)

我真的不知道wordpress的问题,但基本的逻辑是搜索url并将其转换为Youtube嵌入代码,添加它周围的东西!我认为preg_replace()是您必须记住的!