Skip to content

Documentation

PHP SDK: Dom: Finding Elements in HTML

Obtain $dom from $response->dom() or $ctx->dom($html, $baseUrl). A CSS selector identifies an element, for example .product-card, h1, or [data-sku]. A restricted subset of CSS is supported; check selectors in the mapper.

SDK reference

Methods

q

q(string $css): ?Node

Find the first HTML element matching a CSS selector.

$card = $dom->q('.product-card');
if ($card === null) { $ctx->abort('Product card not found'); }

Result and notes. Returns a Node or null. Do not call methods on null without a check or the ?-> operator.

qa

qa(string $css): array

Find all matching HTML elements.

foreach ($dom->qa('.product-card') as $card) {
    $ctx->emit(['name' => $card->text()]);
}

Result and notes. Returns a list of Nodes, or an empty list if nothing matches.

first

first(array $cascade): ?Node

Try several selectors and take the first match found.

$title = $dom->first(['h1.product-title', '.product-name', 'h1'])?->text();

Result and notes. Returns a Node or null. Order matters: selectors are checked from left to right.

text

text(string $css, ?string $default = null): ?string

Get the first match's text without an intermediate Node variable.

$title = $dom->text('h1', 'Untitled');

Result and notes. Returns a string or default (null by default). The default applies when no element exists; it does not replace empty text inside a found element.

attr

attr(string $css, string $attribute, ?string $default = null): ?string

Read an attribute from the first matching element.

$sku = $dom->attr('.product-card', 'data-sku', '');

Result and notes. Returns a string or the default. Use q(...)?->abs(...) for a complete URL.

maxNumber

maxNumber(string $css): ?int

Find the largest number in element text, such as the last page number.

$lastPage = $dom->maxNumber('.pagination a') ?? 1;

Result and notes. Returns an integer or null. The first integer in each text is used; arrows without numbers are skipped.

numbersByPattern

numbersByPattern(string $pattern, string $subject): array

Extract all numbers from the first capturing group of a regular expression applied to the supplied string.

$numbers = $dom->numbersByPattern('/page=(\d+)/', 'page=1 page=12');

Result and notes. Returns a list of integers, [1, 12] in this example. The method searches subject, not the full HTML automatically; the pattern must contain a capturing group.