Skip to content

API reference ​

All classes are in the Tomaj\Scraper namespace and final; extension happens through ParserInterface. Version 5.x, PHP 8.4+.

ClassKindPage
ScraperserviceFetching pages
MetaresultThe Meta object
Author, Section, Tagreadonly valuesThe Meta object
Parser\ParserInterfaceinterfaceWriting a parser
Parser\OgParserparserMeta tags and Open Graph
Parser\OgDomParserparserMeta tags and Open Graph
Parser\SchemaParserparserschema.org JSON-LD
Exception\ScraperExceptioninterfaceError handling
Exception\FetchExceptionexceptionError handling
Exception\MissingExtensionExceptionexceptionError handling

Scraper ​

php
final class Scraper
{
    public function __construct(array $guzzleOptions = [], ?\GuzzleHttp\ClientInterface $httpClient = null);
    public function parseUrl(string $url, array $parsers): Meta;
    public function parse(string $content, array $parsers): Meta;
    public function getBody(): string;
}

__construct() ​

ParameterTypeDefaultDescription
$guzzleOptionsGuzzleOptions (array shape)[]Without $httpClient: configuration of the Guzzle client the scraper creates, merged with array_merge() over ['connect_timeout' => 5, 'headers' => ['User-Agent' => 'Tomaj\Scraper']]. With $httpClient: request options sent with every request. Keys: see Configuration reference.
$httpClient?GuzzleHttp\ClientInterfacenullYour own configured Guzzle client, used as it is (the defaults are not applied).

The Guzzle client is created once, here. Throws nothing.

parseUrl() ​

ParameterTypeDescription
$urlstringThe URL to download with GET.
$parsersarray<ParserInterface>Parsers to run, in order of priority. May be empty.

Returns Meta: the merged result of the parsers on the downloaded body. Throws Exception\FetchException when Guzzle throws (connection error, timeout, TLS error, too many redirects, a 4xx/5xx response unless http_errors is false). Side effect: on success, stores the body for getBody().

Does not validate $url; see Security before passing URLs from users.

parse() ​

ParameterTypeDescription
$contentstringThe HTML (or any string).
$parsersarray<ParserInterface>Parsers to run, in order of priority. May be empty.

Returns a new Meta: for each parser in order, $meta->merge($parser->parse($content)). An empty parser list gives an empty Meta. Throws nothing itself (only what a custom parser throws).

getBody() ​

Returns string: the body downloaded by the last successful parseUrl() call, '' before the first one.

Meta ​

A mutable result object. Every setter and adder returns $this (Meta).

MethodReturnsNotes
getTitle() / setTitle(string $title)?string / Meta
getDescription() / setDescription(string $description)?string / Meta
getKeywords() / setKeywords(string $keywords)?string / Metathe whole content, not split
getAuthors()list<Author>
addAuthor(Author $author)Metaappends
addAuthorByName(string $name)MetaaddAuthor(new Author(null, $name))
getSections()list<Section>
addSection(Section $section)Metaappends
addSectionByName(string $name)MetaaddSection(new Section(null, $name))
getTags()list<Tag>
addTag(Tag $tag)Metaappends
getOgType() / setOgType(string $ogType)?string / Meta
getOgTitle() / setOgTitle(string $ogTitle)?string / Meta
getOgDescription() / setOgDescription(string $ogDescription)?string / Meta
getOgUrl() / setOgUrl(string $ogUrl)?string / Meta
getOgSiteName() / setOgSiteName(string $ogSiteName)?string / Meta
getOgImage() / setOgImage(string $ogImage)?string / Meta
getPublishedTime() / setPublishedTime(DateTimeInterface|string $publishedTime)?DateTimeImmutable / Metaa string is parsed with its offset; a string that is not an absolute date is ignored; a DateTimeInterface is copied (Dates)
getModifiedTime() / setModifiedTime(DateTimeInterface|string $modifiedTime)?DateTimeImmutable / Metaas above
merge(Meta $meta)Meta ($this)copies each value of $meta into fields of $this that are empty (null, '', '0', []); lists are copied whole

The constructor takes no arguments; every field starts as null or [].

Author, Section, Tag ​

php
final readonly class Author // Section and Tag have the same shape
{
    public function __construct(?string $id, ?string $name);
    public function id(): ?string;    // schema.org @id, or null
    public function name(): ?string;
}

id() is set by SchemaParser for authors, articleTerms sections and about tags that have an @id; it is null for values from meta tags and for plain-string JSON-LD values.

ParserInterface ​

php
namespace Tomaj\Scraper\Parser;

interface ParserInterface
{
    public function parse(string $content): Meta;
}

Contract: return a new Meta on every call, do not throw on malformed input, do not keep state between calls.

OgParser ​

Tomaj\Scraper\Parser\OgParser implements ParserInterface. Constructor without arguments. parse() reads <title>, the description, keywords and author meta tags and the Open Graph / article: properties with regular expressions; first occurrence of each tag, null for a tag whose content comes before name/property. See OgParser.

OgDomParser ​

Tomaj\Scraper\Parser\OgDomParser implements ParserInterface.

  • __construct(): throws Exception\MissingExtensionException when ext-dom or ext-libxml is not loaded.
  • parse(string $content): Meta: the same tags as OgParser, with the HTML5 parser Dom\HTMLDocument; any attribute order, case-insensitive attribute values, all author and article:section tags, the last occurrence of the other tags; entities decoded once; declared charsets decoded, UTF-8 otherwise. See OgDomParser.

SchemaParser ​

Tomaj\Scraper\Parser\SchemaParser implements ParserInterface. Constructor without arguments. parse() reads schema.org JSON-LD: the id="schema" block, else the first article node, else the first web page node, with @graph and @id references resolved. See schema.org JSON-LD for the node selection and the field mapping.

ScraperException ​

interface Tomaj\Scraper\Exception\ScraperException extends \Throwable, implemented by every exception of the package.

FetchException ​

final class Tomaj\Scraper\Exception\FetchException extends \RuntimeException implements ScraperException

MemberDescription
public readonly string $urlThe URL passed to parseUrl().
getPrevious()The GuzzleHttp\Exception\GuzzleException that caused it.
getMessage()Cannot fetch "<url>": <Guzzle message>
__construct(string $url, \Throwable $previous)Code 0.

MissingExtensionException ​

final class Tomaj\Scraper\Exception\MissingExtensionException extends \LogicException implements ScraperException

MemberDescription
__construct(string $parser, string $extension)Message: <parser class> requires the PHP extension "<extension>".

Released under the MIT License.