yarri/essence

从网络上提取关于媒体的信息,如YouTube视频、Twitter状态或博客文章。

3.5.4.1 2023-03-03 13:28 UTC

README

Essence

Build status Scrutinizer Code Quality Code Coverage Total downloads

Essence是一个简单的PHP库,用于从网站中提取媒体信息,如YouTube视频、Twitter状态或博客文章。

如果您已经使用Essence 2.x.x,请查看迁移指南

安装

composer require essence/essence

示例

Essence设计得非常易于使用。使用库的主要类,您只需几行代码即可检索信息

$Essence = new Essence\Essence();
$Media = $Essence->extract('http://www.youtube.com/watch?v=39e3KYAmXK4');

if ($Media) {
	// That's all, you're good to go !
}

然后,您可以使用这些数据做任何您想做的事情

<article>
	<header>
		<h1><?php echo $Media->title; ?></h1>
		<p>By <?php echo $Media->authorName; ?></p>
	</header>

	<div class="player">
		<?php echo $Media->html; ?>
	</div>
</article>

您将获得什么

使用Essence,您主要将与Media对象交互。Media是一个简单容器,用于存储从URL中提取的所有信息。

以下是它提供的默认属性

  • type
  • version
  • url
  • title
  • description
  • authorName
  • authorUrl
  • providerName
  • providerUrl
  • cacheAge
  • thumbnailUrl
  • thumbnailWidth
  • thumbnailHeight
  • html
  • width
  • height

这些属性是从OEmbed和OpenGraph规范中收集的,并在统一界面中合并。根据这些标准,这些属性应该是一个坚实的起点。

然而,“非标准”属性也可以并将被设置。

以下是您如何操作Media属性的方法

// through dedicated methods
if (!$Media->has('foo')) {
	$Media->set('foo', 'bar');
}

$value = $Media->get('foo');

// or directly like a class attribute
$Media->customValue = 12;

请注意,当html属性不可用时,Essence将始终尝试填充它。

高级用法

Essence类提供了一些有用的实用函数,以确保您将获得一些信息。

提取URL

crawl()crawlUrl()方法允许您从网页中爬取可提取的URL,无论是直接从其源,还是从其URL(在这种情况下,Essence将负责获取源)。

例如,以下是获取博客文章中所有视频URL的方法

$urls = $Essence->crawlUrl('http://www.blog.com/article');
array(2) {
	[0] => 'http://www.youtube.com/watch?v=123456',
	[1] => 'http://www.dailymotion.com/video/a1b2c_lolcat-fun'
}

然后您可以从所有提取的URL中获取信息

$medias = $Essence->extractAll($urls);
array(2) {
	['http://www.youtube.com/watch?v=123456'] => object(Media) {}
	['http://www.dailymotion.com/video/a1b2c_lolcat-fun'] => object(Media) {}
}

在文本中替换URL

Essence可以将文本中的任何可提取的URL替换为其相关信息。默认情况下,任何URL都将被替换为找到的Media的html属性。

echo $Essence->replace('Look at this: http://www.youtube.com/watch?v=123456');
Look at this: <iframe src="http://www.youtube.com/embed/123456"></iframe>

但您可以通过传递回调来执行更多操作,以控制哪些信息将替换URL

echo $Essence->replace($text, function($Media) {
	return <<<HTML
		<p class="title">$Media->title</p>
		<div class="player">$Media->html</div>
HTML;
});
Look at this:
<p class="title">Video title</p>
<div class="player">
	<iframe src="http://www.youtube.com/embed/123456"></iframe>
<div>

这使得构建丰富的模板或甚至集成模板引擎变得容易

echo $Essence->replace($text, function($Media) use ($TwigTemplate) {
	return $TwigTemplate->render($Media->properties());
});

配置提供者

可以向提供者传递一些选项。

例如,OEmbed提供者接受OEmbed规范中指定的maxwidthmaxheight参数。

$options = [
	'maxwidth' => 800,
	'maxheight' => 600
];

$Media = $Essence->extract($url, $options);
$medias = $Essence->extractAll($urls, $options);
$text = $Essence->replace($text, null, $options);

其他提供者将忽略它们无法处理的选项。

配置

Essence目前支持68个专业提供者

23hq                Deviantart          Kickstarter         Sketchfab
Animoto             Dipity              Meetup              SlideShare
Aol                 Dotsub              Mixcloud            SoundCloud
App.net             Edocr               Mobypicture         SpeakerDeck
Bambuser            Flickr              Nfb                 Spotify
Bandcamp            FunnyOrDie          Official.fm         Ted
Blip.tv             Gist                Polldaddy           Twitter
Cacoo               Gmep                PollEverywhere      Ustream
CanalPlus           HowCast             Prezi               Vhx
Chirb.it            Huffduffer          Qik                 Viddler
CircuitLab          Hulu                Rdio                Videojug
Clikthrough         Ifixit              Revision3           Vimeo
CollegeHumor        Ifttt               Roomshare           Vine
Coub                Imgur               Sapo                Wistia
CrowdRanking        Instagram           Screenr             WordPress
DailyMile           Jest                Scribd              Yfrog
Dailymotion         Justin.tv           Shoudio             Youtube

以及OEmbedOpenGraph提供者,可用于提取任何URL。

您可以在实例化时配置这些提供者

$Essence = new Essence\Essence([
	// the SoundCloud provider is an OEmbed provider with a specific endpoint
	'SoundCloud' => Essence\Di\Container::unique(function($C) {
		return $C->get('OEmbedProvider')->setEndpoint(
			'http://soundcloud.com/oembed?format=json&url=:url'
		);
	}),

	'filters' => [
		// the SoundCloud provider will be used for URLs that matches this pattern
		'SoundCloud' => '~soundcloud\.com/[a-zA-Z0-9-_]+/[a-zA-Z0-9-]+~i'
	]
]);

您还可以禁用默认的提供者

$Essence = new Essence\Essence([
	'filters' => [
		'SoundCloud' => false
	]
]);

您将在Essence的标准DI容器中找到默认配置(请参阅以下部分)。

自定义

几乎Essence中的任何内容都可以通过依赖注入进行配置。在底层,构造函数使用依赖注入容器来返回一个完全配置的Essence实例。

要自定义Essence的行为,最简单的方法是在构建Essence时配置注入设置

$Essence = new Essence\Essence([
	// the container will return a unique instance of CustomHttpClient
	// each time an HTTP client is needed
	'Http' => Essence\Di\Container::unique(function() {
		return new CustomHttpClient();
	})
]);

默认注入设置定义在Standard容器类中。

试试看

一旦您安装了精华,您应该在终端中尝试运行 ./cli/essence.php。此脚本允许您快速测试精华

# will fetch and print information about the video
./cli/essence.php extract http://www.youtube.com/watch?v=4S_NHY9c8uM

# will fetch and print all extractable URLs found at the given HTML page
./cli/essence.php crawl http://www.youtube.com/watch?v=4S_NHY9c8uM

第三方库

如果您对嵌入视频感兴趣,您应该看看 多人游戏 库。它允许您轻松构建可定制的嵌入代码

$Multiplayer = new Multiplayer\Multiplayer();

if ($Media->type === 'video') {
	echo $Multiplayer->html($Media->url, [
		'autoPlay' => true,
		'highlightColor' => 'BADA55'
	]);
}