Get info from any web service or page
[!IMPORTANT]
Searching for maintainer
After several years working on Embed, I don't have the time or motivation to continue maintaining this project. I rarely write PHP code and am not aware of the latest features of PHP. If anyone wants to continue maintaining and evolving this library, please open an issue or contact me.
Meanwhile, I'll continue accepting PR from the community (I don't want this project to die), but won't be actively working on improving it. Thanks!
[][link-packagist] [![Total Downloads][ico-downloads]][link-packagist] [![Monthly Downloads][ico-m-downloads]][link-packagist]
PHP library to get information from any web page (using oembed, opengraph, twitter-cards, scrapping the html, etc). It's compatible with any web service (youtube, vimeo, flickr, instagram, etc) and has adapters to some sites like (archive.org, github, facebook, etc).
Requirements:
If you need PHP 5.5-7.3 support, use the 3.x version
Run php -S localhost:8888 demo/index.php
This package is installable and autoloadable via Composer as embed/embed.
$ composer require embed/embed
…
use Embed\Embed;
$embed = new Embed();
//Load multiple urls asynchronously:
$infos = $embed->getMulti(
'https://www.youtube.com/watch?v=PP1xn5wHtxE',
'https://twitter.com/carlosmeixidefl/status/1230894146220625933',
'https://en.wikipedia.org/wiki/Tordoia',
);
foreach ($infos as $info) {
echo $info->title;
}
The document is the object that store the html code of the page. You can use it to extract extra info from the html code:
//Get the document object
$document = $info->getDocument();
$document->link('image_src'); //Returns the href of a <link>
$document->getDocument(); //Returns the DOMDocument instance
$html = (string) $document; //Returns the html code
$document->select('.//h1'); //Search
You can perform xpath queries in order to select specific elements. A search always return an instance of a Embed\QueryResult:
…
For convenience, the object Metas stores the value of all <meta> elements located in the html, so you can get the values easier. The key of every meta is get from the name, property or itemprop attributes and the value is get from content.
//Get the Metas object
$metas = $info->getMetas();
$metas->all(); //Return all values
$metas->get('og:title'); //Return a key value
$metas->str('og:title'); //Return the value as string (remove html tags)
$metas->html('og:description'); //Return the value as html
$metas->int('og:video:width'); //Return the value as integer
$metas->url('og:url'); //Return the value as full url (converts relative urls to absolutes)
In addition to the html and metas, this library uses oEmbed endpoints to get additional data. You can get this data as following:
//Get the oEmbed object
$oembed = $info->getOEmbed();
$oembed->all(); //Return all raw data
$oembed->get('title'); //Return a key value
$oembed->str('title'); //Return the value as string (remove html tags)
$oembed->html('html'); //Return the value as html
$oembed->int('width'); //Return the value as integer
$oembed->url('url'); //Return the value as full url (converts relative urls to absolutes)
Additional oEmbed parameters (like instagrams hidecaption) can also be provided:
$embed = new Embed();
$result = $embed->get('https://www.instagram.com/p/B_C0wheCa4V/');
$result->setSettings([
'oembed:query_parameters' => ['hidecaption' => true]
]);
$oembed = $info->getOEmbed();
Another API available by default, used to extract info using the JsonLD schema.
//Get the linkedData object
$ld = $info->getLinkedData();
$ld->all(); //Return all data
$ld->get('name'); //Return a key value
$ld->str('name'); //Return the value as string (remove html tags)
$ld->html('description'); //Return the value as html
$ld->int('width'); //Return the value as integer
$ld->url('url'); //Return the value as full url (converts relative urls to absolutes)
Some sites like Wikipedia or Archive.org provide a custom API that is used to fetch more reliable data. You can get the API object with the method getApi() but note that not all results have this method. The Api object has the same methods than oEmbed:
//Get the API object
$api = $info->getApi();
$api->all(); //Return all raw data
$api->get('title'); //Return a key value
$api->str('title'); //Return the value as string (remove html tags)
$api->html('html'); //Return the value as html
$api->int('width'); //Return the value as integer
$api->url('url'); //Return the value as full url (converts relative urls to absolutes)
Depending of your needs, you may want to extend this library with extra features or change the way it makes some operations.
Embed use some PSR standards to be the most interoperable possible:
Embed comes with a CURL client compatible with PSR-18 but you need to install a PSR-7 / PSR-17 library. Here you can see a list of popular libraries and the library can detect automatically 'laminas\diactoros', 'guzzleHttp\psr7', 'slim\psr7', 'nyholm\psr7' and 'sunrise\http' (in this order). If you want to use a different PSR implementation, you can do it in this way:
use Embed\Embed;
use Embed\Http\Crawler;
$client = new CustomHttpClient();
$requestFactory = new CustomRequestFactory();
$uriFactory = new CustomUriFactory();
//The Crawler is responsible for perform http queries
$crawler = new Crawler($client, $requestFactory, $uriFactory);
//Create an embed instance passing the Crawler
$embed = new Embed($crawler);
There are some sites with special needs: because they provide public APIs that allows to extract more info (like Wikipedia or Archive.org) or because we need to change how to extract the data in this particular site. For all that cases we have the adapters, that are classes extending the default classes to provide extra functionality.
Before creating an adapter, you need to understand how Embed work: when you execute this code, you get a Extractor class
//Get the Extractor with all info
$info = $embed->get($url);
//The extractor have document and oembed:
$document = $info->getDocument();
$oembed = $info->getOEmbed();
The Extractor class has many Detectors. Each detector is responsible to detect a specific piece of info. For example, there's a detector for the title, other for description, image, code, etc.
So, an adapter is basically an extractor created specifically for a site. It can contains also custom detectors or apis. If you see the src/Adapters folder you can see all adapters.
If you create an adapter, you need also register to Embed, so it knows in which website needs to use. To do that, there's the ExtractorFactory object, that is responsible for instantiate the right extractor for each site.
use Embed\Embed;
$embed = new Embed();
$factory = $embed->getExtractorFactory();
//Use this MySite adapter for mysite.com
$factory->addAdapter('mysite.com', MySite::class);
//Remove the adapter for pinterest.com, so it will use the default extractor
$factory->removeAdapter('pinterest.com');
//Change the default extractor
$factory->setDefault(CustomExtractor::class);
Embed comes with several predefined detectors, but you may want to change or add more. Just create a class extending Embed\Detectors\Detector class and register it in the extractor factory. For example:
use Embed\Embed;
use Embed\Detectors\Detector;
class Robots extends Detector
{
public function detect(): ?string
{
$response = $this->extractor->getResponse();
$metas = $this->extractor->getMetas();
return $response->getHeaderLine('x-robots-tag'),
?: $metas->str('robots');
}
}
//Register the detector
$embed = new Embed();
$embed->getExtractorFactory()->addDetector('robots', Robots::class);
//Use it
$info = $embed->get('http://example.com');
$robots = $info->robots;
If you need to pass settings to the CurlClient to perform http queries:
…
If you need to pass settings to your detectors, you can add settings to the ExtractorFactory:
use Embed\Embed;
$embed = new Embed();
$embed->setSettings([
'oembed:query_parameters' => [], //Extra parameters send to oembed
'twitch:parent' => 'example.com', //Required to embed twitch videos as iframe
'facebook:token' => '1234|5678', //Required to embed content from Facebook
'instagram:token' => '1234|5678', //Required to embed content from Instagram
'twitter:token' => 'asdf', //Improve the data from twitter
]);
$info = $embed->get($url);
Note: The built-in detectors does not require settings. This feature is only for convenience if you create a specific detector that requires settings.
composer test
# or
./vendor/bin/phpunit
The test suite uses cached HTTP responses and fixtures to avoid network requests during testing. You can control this behavior using environment variables:
Environment Variable DescriptionUPDATE_EMBED_SNAPSHOTS=1
Fetch from network and update both cache and fixtures
EMBED_STRICT_CACHE=1
Fail if cache or fixture doesn't exist (useful for CI)
By default (no environment variables set), tests read from cache and generate missing files automatically.
Note: If both UPDATE_EMBED_SNAPSHOTS and EMBED_STRICT_CACHE are set, UPDATE_EMBED_SNAPSHOTS takes precedence.
The test framework uses two types of cached data:
tests/cache/): Cached HTTP responses from external sitestests/fixtures/): Expected test results (metadata extracted from cached responses)If a website updates its HTML and you need to update the cached response and fixture:
# Update cache and fixture for a specific test
UPDATE_EMBED_SNAPSHOTS=1 ./vendor/bin/phpunit --filter testYoutube
After adding a new URL to test:
# This will fetch the response and create both cache and fixture
UPDATE_EMBED_SNAPSHOTS=1 ./vendor/bin/phpunit --filter testNewSite
To refresh all cached responses and fixtures from the network:
UPDATE_EMBED_SNAPSHOTS=1 ./vendor/bin/phpunit
Ensure all tests run strictly from cache (fail if any cache is missing):
EMBED_STRICT_CACHE=1 ./vendor/bin/phpunit
[
No open issues yet, or sync has not completed.