Writing a parser
The built-in parsers read meta tags, Open Graph and JSON-LD. For anything else (Twitter cards, microdata, a site's own markup, data in the page body) implement ParserInterface:
namespace Tomaj\Scraper\Parser;
use Tomaj\Scraper\Meta;
interface ParserInterface
{
public function parse(string $content): Meta;
}Rules
- Return a new
Metafrom every call. One parser instance is used for many pages; keeping aMetain a property leaks values from one page into the next. - Do not throw on bad input. Return what you could read. Throw only for programming errors, such as a missing extension (do that in the constructor, like
OgDomParser). - Set only what you found. An unset field stays
nulland a later parser can fill it. - Do not depend on other parsers. Each parser gets the original HTML; the scraper merges the results.
- The built-in classes are
final: wrap them instead of extending them.
Meta has no fields of its own for other markup. Map what you read to the closest field (a Twitter card title to setOgTitle()), or keep your own result next to the Meta.
A short one
<?php
declare(strict_types=1);
require_once __DIR__ . '/../../vendor/autoload.php';
use Tomaj\Scraper\Meta;
use Tomaj\Scraper\Parser\OgParser;
use Tomaj\Scraper\Parser\ParserInterface;
use Tomaj\Scraper\Scraper;
/**
* Reads the Twitter card tags as a fallback for pages without Open Graph.
*/
final class TwitterCardParser implements ParserInterface
{
#[\Override]
public function parse(string $content): Meta
{
$meta = new Meta();
$fields = [
'twitter:title' => $meta->setOgTitle(...),
'twitter:description' => $meta->setOgDescription(...),
'twitter:image' => $meta->setOgImage(...),
];
foreach ($fields as $name => $setter) {
$pattern = '/<meta\s+name="' . preg_quote($name, '/') . '"\s+content="([^"]*)"/i';
if (preg_match($pattern, $content, $matches) === 1) {
$setter(html_entity_decode($matches[1], ENT_QUOTES | ENT_HTML5));
}
}
return $meta;
}
}
$html = '<meta name="twitter:title" content="Only a Twitter card">'
. '<meta name="twitter:image" content="https://example.com/card.png">';
$meta = new Scraper()->parse($html, [new OgParser(), new TwitterCardParser()]);
echo $meta->getOgTitle(), "\n";
echo $meta->getOgImage(), "\n";Output:
Only a Twitter card
https://example.com/card.pngA complete one: Twitter cards
The Twitter card example has a parser built on PHP 8.4's HTML5 parser (Dom\HTMLDocument, like OgDomParser) that reads twitter:title, twitter:description and twitter:image (also written as property="twitter:…"):
<?php
declare(strict_types=1);
namespace App;
use Tomaj\Scraper\Meta;
use Tomaj\Scraper\Parser\ParserInterface;
/**
* Reads Twitter (X) card tags into the Open Graph fields of Meta.
*
* The built-in parsers do not read twitter:* tags. Put this parser after them, so the card is
* only a fallback for pages without Open Graph:
*
* $scraper->parse($html, [new OgDomParser(), new TwitterCardParser()]);
*/
final class TwitterCardParser implements ParserInterface
{
#[\Override]
public function parse(string $content): Meta
{
// a new Meta from every call: one parser instance is used for many pages
$meta = new Meta();
if ($content === '') {
return $meta;
}
// the HTML5 parser of PHP 8.4: UTF-8 unless the page declares another charset,
// LIBXML_NOERROR keeps parse errors of real-world markup from becoming warnings
$dom = \Dom\HTMLDocument::createFromString($content, LIBXML_NOERROR);
foreach ($dom->querySelectorAll('meta[name], meta[property]') as $tag) {
// cards are written with name="twitter:…", some sites use property="twitter:…"
$name = strtolower(($tag->getAttribute('name') ?: $tag->getAttribute('property')) ?? '');
$value = $tag->getAttribute('content') ?? '';
if ($value === '') {
continue;
}
match ($name) {
'twitter:title' => $meta->setOgTitle($value),
'twitter:description' => $meta->setOgDescription($value),
'twitter:image', 'twitter:image:src' => $meta->setOgImage($value),
default => null,
};
}
return $meta;
}
}Put it after the built-in parsers so it only fills what they did not find:
$parsers = [new OgDomParser(), new TwitterCardParser()];Wrapping a built-in parser
To post-process the result of a built-in parser, compose it:
final class AbsoluteImageParser implements ParserInterface
{
public function __construct(
private readonly string $pageUrl,
private readonly ParserInterface $inner = new OgDomParser(),
) {}
#[\Override]
public function parse(string $content): Meta
{
$meta = $this->inner->parse($content);
$image = $meta->getOgImage();
if ($image !== null && str_starts_with($image, '/') && !str_starts_with($image, '//')) {
$parts = parse_url($this->pageUrl);
$meta->setOgImage($parts['scheme'] . '://' . $parts['host'] . $image);
}
return $meta;
}
}
$meta = new AbsoluteImageParser('https://shop.example/p/1')->parse('<meta property="og:image" content="/img/1.jpg">');
echo $meta->getOgImage(), "\n";https://shop.example/img/1.jpgTesting a parser
A parser is a pure function of a string, so test it with HTML fixtures and no network:
final class TwitterTitleParser implements ParserInterface
{
#[\Override]
public function parse(string $content): Meta
{
$meta = new Meta();
if (preg_match('/<meta\s+name="twitter:title"\s+content="([^"]*)"/i', $content, $m) === 1) {
$meta->setOgTitle(html_entity_decode($m[1], ENT_QUOTES | ENT_HTML5));
}
return $meta;
}
}
$parser = new TwitterTitleParser();
var_dump($parser->parse('<meta name="twitter:title" content="Tom & Jerry">')->getOgTitle() === 'Tom & Jerry');
var_dump($parser->parse('')->getOgTitle() === null);
var_dump($parser->parse('<meta name="twitter:title" content="A">') !== $parser->parse('<meta name="twitter:title" content="A">'));bool(true)
bool(true)
bool(true)Test it together with the built-in parsers too, through Scraper::parse(), to see the merged result your application gets. See Testing your code.