Install the PHP library using composer:
composer require hyvor/unfold
Call Unfold::embed()
to get the embed code for a URL of a
supported platform. This returns an UnfoldedEmbed
object.
<?php
use Hyvor\Unfold\Unfold;
use Hyvor\Unfold\Exception\EmbedUnableToResolveException;
use Hyvor\Unfold\Exception\UnfoldException;
try {
$embed = Unfold::embed('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
$embed->embed; // html code to embed
$embed->durationMs; // duration to resolve the embed in milliseconds
} catch (EmbedUnableToResolveException) {
// This URL did not match any of the supported platforms
} catch (UnfoldException $e) {
// any other possible error
// $e->getMessage();
}
Call Unfold::link()
to get metadata of a URL. This returns an
UnfoldedLink
object.
<?php
use Hyvor\Unfold\Unfold;
use Hyvor\Unfold\Exception\UnfoldException;
use Hyvor\Unfold\Exception\LinkScrapeException;
try {
$link = Unfold::link('https://hyvor.com');
$link->title;
$link->description;
$link->siteName;
$link->siteUrl;
$link->canonicalUrl;
$link->publishedTime;
$link->modifiedTime;
$link->thumbnailUrl;
$link->iconUrl;
$link->locale;
$link->authors;
$link->tags;
$link->durationMs;
} catch (LinkScrapeException $e) {
// This URL could not be scraped due to non-200 status code or other reasons
// $e->getMessage(); returns more details including the HTTP status
} catch (UnfoldException $e) {
// any other possible error
// $e->getMessage();
}
Both embed()
and link()
methods accept an optional second parameter that
accepts a Hyvor\Unfold\UnfoldConfig
.
Here is an example with all the available configurations (feel free to read the comments in the code for more details):
use Hyvor\Unfold\Unfold;
use Hyvor\Unfold\UnfoldConfig;
$url = 'https://hyvor.com';
$config = new UnfoldConfig(
httpClient: new MyCustomPsr18Client(),
httpMaxRedirects: 5,
httpUserAgent: 'My Custom User Agent',
);
$link = Unfold::link($url, $config);
This library does not include an HTTP Client. Instead, it uses php-http/discovery
to
find a PSR-18 HTTP Client installed in your project. If you want to use a custom HTTP Client, you
can pass it as the httpClient
parameter in the UnfoldConfig
object.
Currently, an HTTP Client is only required for the link()
method. The
embed()
method depends on regex to parse URLs into embeds.