Upgrading from meta-scraper 4.x to 5.0
This file lists the changes in 5.0 that may need work in your application. The full list of changes is in CHANGELOG.md.
Checklist:
- PHP 8.4 and Guzzle 7.15.2+ or 8: Requirements.
parseUrl()throwsFetchExceptioninstead of Guzzle exceptions: Exceptions.- Classes are
final, value objects arereadonly,protectedmembers are gone: Final classes. Scraperoptions are typed; options outside the documented list go into your own Guzzle client: Scraper options.OgDomParserthrows withoutext-dom: OgDomParser.- Published and modified times are
DateTimeImmutablewith the page's offset; relative dates are ignored: Times. - Parsers return different (correct) values for some pages: Parser output.
Requirements
- PHP 8.4 or newer (4.x ran on PHP 7.1+).
guzzlehttp/guzzle^7.15.2 || ^8.0.1. Guzzle 6 is no longer supported; older Guzzle 7 releases have published security advisories.
parseUrl() throws FetchException
Before, a failed download let the Guzzle exception escape. Now every failure (connection error, timeout, TLS error, too many redirects, 4xx/5xx response) is a Tomaj\Scraper\Exception\FetchException. The Guzzle exception is its previous exception. All exceptions of the package implement Tomaj\Scraper\Exception\ScraperException.
// 4.x
try {
$meta = $scraper->parseUrl($url, $parsers);
} catch (\GuzzleHttp\Exception\GuzzleException $e) {
// ...
}
// 5.0
try {
$meta = $scraper->parseUrl($url, $parsers);
} catch (\Tomaj\Scraper\Exception\FetchException $e) {
$guzzleException = $e->getPrevious();
$failedUrl = $e->url;
}Classes are final
Scraper, Meta, Author, Section, Tag, OgParser, OgDomParser and SchemaParser are final; Author, Section and Tag are readonly. Scraper::$guzzleOptions, OgDomParser::$meta, OgDomParser::$allowedAttributes, OgDomParser::processMetaTag() and OgDomParser::fixMetaTag() (all protected) are removed.
If you extended a class, compose it instead, or implement ParserInterface:
// 4.x
class MyParser extends OgParser
{
public function parse(string $content): Meta
{
$meta = parent::parse($content);
// ...
return $meta;
}
}
// 5.0
final class MyParser implements ParserInterface
{
public function __construct(private readonly OgParser $og = new OgParser()) {}
public function parse(string $content): Meta
{
$meta = $this->og->parse($content);
// ...
return $meta;
}
}If you changed the default Guzzle options by overriding Scraper::$guzzleOptions, pass them to the constructor instead (next section).
Scraper options and your own Guzzle client
new Scraper(array $guzzleOptions = []) still works and the options are still merged over the defaults (5 second connect timeout, Tomaj\Scraper User-Agent). The options array is now typed for static analysis: connect_timeout, timeout, read_timeout, headers, proxy, allow_redirects, verify, http_errors, decode_content, force_ip_resolve and version. Other Guzzle options still reach Guzzle at runtime, but PHPStan and Psalm report them. For those, pass your own client as the second argument; the defaults are not applied to it, and the options array becomes request options:
// 4.x
$scraper = new Scraper(['handler' => $stack, 'cookies' => true]);
// 5.0
$scraper = new Scraper([], new \GuzzleHttp\Client([
'handler' => $stack,
'cookies' => true,
'connect_timeout' => 5,
'headers' => ['User-Agent' => 'MyBot/1.0'],
]));The client is created once in the constructor instead of on every parseUrl() call.
OgDomParser requires ext-dom and ext-libxml
Without ext-dom or ext-libxml, new OgDomParser() used to succeed and then fail inside parse() (or find nothing). It now throws Tomaj\Scraper\Exception\MissingExtensionException (a LogicException). Use OgParser where the extensions are not available.
Published and modified times
Meta::getPublishedTime() and getModifiedTime() return ?DateTimeImmutable instead of ?DateTime (#36). The setters accept any DateTimeInterface (stored as a copy) or a string.
- Immutable.
modify(),setTimezone()and friends return a new object and no longer change theMeta. Code that called them for their side effect must use the return value. Code that typed a variable or parameter asDateTimemust acceptDateTimeImmutable(orDateTimeInterface). - The page's offset is kept. 4.x converted every string to UTC:
2018-12-15T19:00:26+02:00came back as2018-12-15T17:00:26+00:00. Now it comes back with+02:00; the instant is the same, so comparisons and timestamps do not change, butformat()shows the page's local time. CallsetTimezone()for the zone you display. - Only absolute dates. 4.x used
strtotime(), which also accepted relative expressions (yesterday noon,+1 week,now) and resolved them against the server's clock. Those, a time without a date, a Unix timestamp (@1763616600), an invalid date (2026-02-30) and an RFC 2822 date whose weekday does not match are now ignored (the field stays as it was). A string without an offset is still in the default time zone.
// 4.x
$published = $meta->getPublishedTime(); // DateTime in UTC
$published->setTimezone(new DateTimeZone('Europe/Bratislava')); // also changed $meta
echo $published->format('j. n. Y H:i');
// 5.0
$published = $meta->getPublishedTime(); // DateTimeImmutable with the page's offset
echo $published?->setTimezone(new DateTimeZone('Europe/Bratislava'))->format('j. n. Y H:i');Parser output changes
These are bug fixes, but they change what the parsers return:
OgDomParserreturns a newMetafrom everyparse()call. Before, one parser instance returned the same object every time, with authors and sections piling up across pages (#21). If you relied on that accumulation, merge the results yourself withMeta::merge().OgDomParserreads documents without a charset declaration as UTF-8. Before, their non-ASCII text came back garbled (Žltýinstead ofŽltý) (#22).SchemaParserreads standard JSON-LD (<script type="application/ld+json">withoutid="schema", multiline JSON, several blocks,@graph,{"@id": …}references). Pages that used to give an empty result fromSchemaParsermay now return a title, authors, dates and more. WhenSchemaParserruns first, its values win over the Open Graph ones, sogetTitle()may now be the article headline instead of the<title>(#23). Pages with anid="schema"block keep using it.SchemaParseralso readsimageas a URL string, a list or anImageObjectwith only acontentUrl(#30). When it runs before an Open Graph parser,getOgImage()may now be the JSON-LD image instead ofog:image.OgDomParserno longer changes thelibxml_use_internal_errors()setting; 4.x left internal errors switched on for the rest of the process.OgDomParserparses with the HTML5 parser of PHP 8.4 (Dom\HTMLDocument) instead of libxml's HTML 4 parser (#34). Entities are decoded once: a double-escapedTom &amp; Jerryis nowTom & Jerry(4.x returnedTom & Jerry), and HTML5-only entities such asčare decoded. A charset declaration is read from the first 1024 bytes like in a browser; later declarations and XML declarations are still used for pages that are not valid UTF-8. Values are always valid UTF-8. A<title>inside an inline<svg>is no longer taken as the page title.OgParserreturnsnullfor a tag it cannot read (contentbeforename/property, nocontent) and an empty string forcontent="". 4.x returned the content of a later tag or a piece of markup instead. Values with the other quote character (content="Don't") are no longer cut at it (#29).OgParserdecodes every HTML entity (é,…, ,–…), not only&,<,>,"and'. Code that decoded the values a second time may now decode text that the page meant literally; becomes U+00A0, not a plain space (#35).
See also
- Changelog: every change of 5.0.
- Error handling:
FetchExceptionand the Guzzle exceptions behind it. - Configuration reference: the typed
Scraperoptions. - Choosing a parser:
OgDomParserand its requirements.