Skip to content

Choosing a parser ​

A parser implements Tomaj\Scraper\Parser\ParserInterface: it gets the HTML as a string and returns a new Meta. The package has three:

OgParserOgDomParserSchemaParser
Reads<title>, meta tags, Open Graph<title>, meta tags, Open Graphschema.org JSON-LD
Howregular expressionsHTML5 parser of PHP 8.4 (Dom\HTMLDocument)regular expression for the <script> blocks, json_decode()
Needsnothingext-dom, ext-libxmlext-json (always on)
Attribute ordername/property must come before contentanyany
Repeated tags (article:section)first one onlyall of themlists in JSON
Character setbytes as they aredeclared charset decoded, otherwise UTF-8bytes as they are
Authors, sections, tags with @idnonoyes
PageMeta tags and Open GraphMeta tags and Open Graphschema.org JSON-LD

Which ones, in which order ​

The order decides which value wins when two parsers find the same field (Combining parsers).

Use caseParsers
News and blog articles: clean headlines, structured authors with @id, dates[new SchemaParser(), new OgDomParser()]
Link previews: what the page shows when shared on social networks[new OgDomParser(), new SchemaParser()]
No ext-dom, or speed over accuracy on well-formed pages[new SchemaParser(), new OgParser()]
Pages with only Twitter cards or other markupadd your own parser at the end

OgDomParser is the better choice for meta tags whenever ext-dom is available: OgParser relies on the attribute order and finds nothing in tags that write content before property (see the broken pages example). OgParser stays for environments without ext-dom and for compatibility.

Creating parsers ​

All three have a constructor without arguments and keep no state between calls, so create them once and reuse them:

php
$parsers = [new SchemaParser(), new OgDomParser()];

foreach ([$html, $html] as $page) {
    echo new Scraper()->parse($page, $parsers)->getTitle(), "\n";
}
text
Ten tips for PHP 8.4
Ten tips for PHP 8.4

new OgDomParser() throws MissingExtensionException when ext-dom or ext-libxml is not loaded, so a missing extension shows up when the parser is created, not later as empty results.

A parser can also be used without the Scraper:

php
$meta = new SchemaParser()->parse($html);
echo $meta->getAuthors()[0]->id(), "\n";
text
https://blog.example/#jana

Released under the MIT License.