lapalabs / youtube-helper
一个用于方便处理YouTube媒体资源的小巧包。允许从资源URL中提取ID并构建有效的资源URL。
Requires
- php: >=5.4.0
Requires (Dev)
- phpunit/phpunit: ~4.7
This package is auto-updated.
Last update: 2024-08-29 04:13:44 UTC
README
一个用于方便处理YouTube媒体资源的小巧包。允许从资源URL中提取ID并构建有效的资源URL。
安装
使用 Composer
将包安装到您的项目中
$ composer require lapalabs/youtube-helper dev-master
用法
创建
您可以轻松创建有效的YouTube资源对象
use LapaLabs\YoutubeExtractor\Resource\YoutubeResource; // Build resource object from valid YouTube resource ID $resource = new YoutubeResource('5qanlirrRWs'); // or with static method $resource = YoutubeResource::create('5qanlirrRWs'); // or create from valid YouTube resource URL $resource = YoutubeResource::createFromUrl('https://www.youtube.com/watch?v=5qanlirrRWs');
此库支持一些有效的YouTube资源URL,应在 YoutubeResource::createFromUrl()
方法中使用
https://youtube.com/watch?v=5qanlirrRWs
https://m.youtube.com/watch?v=5qanlirrRWs
https://www.youtube.com/watch?v=5qanlirrRWs
https://www.youtube.com/embed/5qanlirrRWs
https://youtu.be/5qanlirrRWs
高级用法
创建资源成功后,您可以访问一系列有用的方法
$resource->getId(); // 5qanlirrRWs $resource->buildEmbedUrl(); // https://www.youtube.com/embed/5qanlirrRWs // other useful methods to build various valid URLs $resource->buildUrl(); // shortcut alias for buildDefaultUrl $resource->buildDefaultUrl(); // https://www.youtube.com/watch?v=5qanlirrRWs $resource->buildAliasUrl(); // https://youtube.com/watch?v=5qanlirrRWs $resource->buildMobileUrl(); // https://m.youtube.com/watch?v=5qanlirrRWs $resource->buildShortUrl(); // https://youtu.be/5qanlirrRWs
您可以得到一个有效的YouTube资源URL数组,这些URL可以在 createFromUrl
方法中使用
YoutubeResource::getValidHosts(); // array of valid YouTube resource URLs
要检查YouTube资源ID或主机是否有效,请使用以下方法
YoutubeResource::isValidId('5qanlirrRWs'); // return true if ID is valid YoutubeResource::isValidHost('youtu.be'); // return true if host is valid
您可以轻松获取嵌入YouTube资源到您页面上的HTML代码
$resource->buildEmbedCode(); // with default attributes returns: <iframe width="560" height="315" src="https://www.youtube.com/embed/5qanlirrRWs" frameborder="0" allowfullscreen></iframe> // to pass any other parameters or override defaults with your own use: $resource->buildEmbedCode([ 'width' => 800, // override default 560 'height' => 600, // override default 315 'class' => 'video', // add new attribute ]);
传递给
buildEmbedCode()
方法的属性仅适用于当前的嵌入HTML代码。要为特定资源全局更改默认属性,您应将属性数组传递给setAttributes()
方法。要获取特定资源的当前默认HTML属性,请使用getAttributes()
方法。
默认有一些属性
[ 'width' => 560, 'height' => 315, 'src' => '', // hold position for specific order 'frameborder' => 0, 'allowfullscreen' => null, ];
注意:
src
属性仅用于构建嵌入HTML代码,将在后台调用buildEmbedUrl()
方法时自动注入。因此,传递给buildEmbedCode()
或setAttributes()
的任何src
值都将被忽略并替换为当前资源的正确URL。您可以像上面示例中那样给出它,以指向HTML代码中的位置。
链接
如果您发现错误或只是想提出改进建议,请随意创建问题 或 Pull Request。