as part of working on our SaaS application, I had to find a way to get some metadata about URLs to generate previews for links.
These sorts of metadata can mostly be grabbed from OG and Meta tags of a web page if they exist. To achieve this I have created PHP Link Preview an open source composer package that makes it easy to parse web pages and grab this information.
So if you are looking to know how to generate link previews using PHP you’re in the right place.
To start using PHP Link Preview Simply install it as a dependency via Composer.
Once you have the package installed and ready to use, you can instantiate the client like the following:
use Hazaveh\LinkPreview\Client;
$client = new Client();
/**
* Returns an instance of Hazaveh\LinkPreview\Model\Link
* {title, description, image, icon, locale}
*/
$preview = $client->parse("https://hazaveh.net/2023/07/re-inventing-bookmarks-for-teams/");
The parser will try to extract pieces of data such as page title, page description, image, page icon, and locale.
Using this information you can generate previews for links in your web application.
However you are not restricted to this information, the client allows you to pass a customer parser which implements ParserInterface and overrides the parsing mechanism.
You can also extend the existing parser by overriding the getExtractors method and adding additional extractors to your logic without any modification to the package code.
Considerations
To make sure you do not run into performance issues, it is advised that you wrap your logic and save the generated previews in a temporary cache, this would help your server to avoid unnecessary crawling to grab data from links that are previously crawled.
I hope you love this package, if you find it interesting please add a star and if you wish to extend or improve the package feel free to open a PR.