Skip to content

Extraction

Markdown is great for language models; your application usually wants data. PAM Crawl offers several ways to turn a page into structured values, from the most explicit to the most automatic:

Approach Use it when
Typed DTOs You know the page layout and want real PHP objects with types.
JSON schemas You have Crawl4AI schemas already, or the schema is data (stored, generated, shared).
Regex patterns You want emails, URLs, dates or prices from any page, without selectors.
Semantic clustering You want topic blocks from unstructured text.
LLM extraction The layout is unknown or varies too much for selectors.

None of the first three needs an LLM, a browser or network access beyond the page itself.

Describe what you want as a PHP class and annotate each constructor parameter (or public property) with where its value comes from:

src/Book.php
use Pam\Crawl\Extract\Absolute;
use Pam\Crawl\Extract\Css;
use Pam\Crawl\Extract\Item;
use Pam\Crawl\Extract\Lower;
use Pam\Crawl\Extract\Money;
use Pam\Crawl\Extract\Regex;
use Pam\Crawl\Extract\Trim;
#[Item('article.product_pod')]
final readonly class Book
{
public function __construct(
#[Css('h3 a', attr: 'title'), Css('h3 a')] public string $title,
#[Css('.price_color'), Money] public int $priceCents, // "£51.77" -> 5177
#[Css('p.star-rating', attr: 'class'), Regex('star-rating\s+(\w+)'), Lower] public string $rating,
#[Css('.availability'), Trim] public string $availability,
#[Css('h3 a', attr: 'href'), Absolute] public string $url,
#[Css('.availability')] public bool $inStock = false, // "In stock" -> true
) {}
}

Then ask a page for one object or for all of them:

books.php
use Pam\Crawl\Crawl;
$page = Crawl::url('https://books.toscrape.com/catalogue/page-1.html')->get();
$books = $page->extractAll(Book::class); // list<Book>, one per article.product_pod
echo count($books), "\n"; // 20
echo $books[0]->title, "\n"; // A Light in the Attic
echo $books[0]->priceCents, "\n"; // 5177
echo $books[0]->url, "\n"; // https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html

The class-level #[Item] attribute names the element that represents one item. Selectors on the properties are then evaluated inside each item. Without #[Item], the whole page is one item.

Method Returns
$page->extract(Book::class) One object, or null when a required field is missing.
$page->extractAll(Book::class) Every item on the page. Items missing a required field are skipped.
$page->extractAll(Book::class, each: 'li.result') Items from a different item selector than #[Item].
$crawler->extract(Book::class) / $crawler->extractAll(Book::class) The same, across every page of a crawl.
Extractor::for(Book::class)->oneOrFail($page) One object, or an ExtractionFailed exception naming the field.

A field is required when it has no default value and is not nullable. Make optional fields nullable (?string $image = null) or give them a default.

Extraction plans are compiled once per class and kept for the life of the PAM worker, so repeated extraction costs only the selector work.

Several source attributes on one property form a fallback chain: the first source that produces a value wins. Transforms (such as Money) apply to whichever source matched:

#[Css('.price'), JsonLd('offers.price', type: 'Product'), Meta('product:price:amount'), Money]
public int $priceCents,

All attributes live in the Pam\Crawl\Extract namespace.

Attribute Reads
Css(string $selector, ?string $attr = null, bool $html = false, bool $all = false) Text of the first match. attr reads an attribute, html the inner HTML, all every match as a list. Selectors starting with / or ./ are treated as XPath.
XPath(string $expression, ?string $attr = null, bool $all = false) The same, with an XPath expression.
JsonLd(string $path, ?string $type = null) A dot path into the page’s JSON-LD nodes, optionally only nodes of one @type.
Meta(string $name) A meta tag by name or property (og:title, description), or a field of $page->meta (title, canonical, lang).
Embedded(string $path) A dot path into hydration data from Next.js, Nuxt, Remix and other apps.
PageValue(string $name) Page-level facts: url, finalUrl, status or title.
Regex(string $pattern, int|string $group = 1) A regex over the item’s text when used alone, or over the previous value when chained.

Dot paths support * for any key and a leading .. to search for a key at any depth: #[Embedded('..product.price')].

Transforms run, in order, on the value a source produced:

Attribute Effect
Absolute Resolves a relative URL against the page. Applied automatically to href and src attributes.
Money Price text to integer cents: "R$ 1.299,90" and "$1,299.90" both become 129990.
Number Locale-tolerant number parsing: "1.234,5", "1,234.5", "12k".
Date(string $format = DATE_ATOM) Parses a date in any common format and formats it.
Trim(string $characters = ...), Lower, Upper String clean-up.
Regex(...) Keeps a capture group of the value.
Using(callable-string|array $callable) Your own function: #[Using([Slug::class, 'of'])].

The property type is respected too: int and float properties are parsed with Number, and bool properties are true for values such as yes, true, 1, in stock, available and the schema.org InStock URL.

Combine all: true with #[Each] to hydrate a list of nested objects, each scoped to its own element:

src/Product.php
use Pam\Crawl\Extract\Css;
use Pam\Crawl\Extract\Each;
use Pam\Crawl\Extract\JsonLd;
use Pam\Crawl\Extract\Money;
final readonly class Variant
{
public function __construct(
#[Css('.color')] public string $color,
#[Css('.stock')] public int $stock,
) {}
}
final readonly class Product
{
/** @param list<Variant> $variants */
public function __construct(
#[Css('h1')] public string $name,
#[Css('.price'), JsonLd('offers.price', type: 'Product'), Money] public int $priceCents,
#[Css('.variant', all: true), Each(Variant::class)] public array $variants = [],
) {}
}
$product = $page->extract(Product::class);

Schemas written for Crawl4AI’s JsonCssExtractionStrategy and JsonXPathExtractionStrategy work unchanged with Pam\Crawl\Extract\Schema. CSS and XPath selectors can be mixed; each one is auto-detected:

quotes.php
use Pam\Crawl\Crawl;
use Pam\Crawl\Extract\Schema;
$schema = Schema::fromArray([
'name' => 'Quotes',
'baseSelector' => 'div.quote',
'absoluteUrls' => true,
'fields' => [
['name' => 'text', 'selector' => 'span.text', 'type' => 'text'],
['name' => 'author', 'selector' => 'small.author', 'type' => 'text'],
['name' => 'author_url', 'selector' => 'span a', 'type' => 'attribute', 'attribute' => 'href'],
['name' => 'tags', 'selector' => 'a.tag', 'type' => 'list', 'fields' => [
['name' => 'tag', 'type' => 'text'],
]],
],
]);
$rows = $schema->extract(Crawl::url('https://quotes.toscrape.com/')->get());
// [['text' => '“The world as we have created it...”', 'author' => 'Albert Einstein',
// 'author_url' => 'https://quotes.toscrape.com/author/Albert-Einstein',
// 'tags' => [['tag' => 'change'], ['tag' => 'deep-thoughts'], ...]], ...]

Schema::fromJson() reads the same structure from a JSON string, and toJson() / toArray() write it back.

Type Value
text The element’s text.
attribute The attribute named by attribute.
html The element’s inner HTML.
regex A capture group (group, default 1) of pattern applied to the text.
nested An object built from fields, scoped to the first match.
list / nested_list A list built from fields, one entry per match.
computed The return value of a PHP callable in function, given the item so far.

type can also be a list of steps, such as ["text", "regex"]. Fields accept default, transform (lower, upper, trim) and source, which moves to a following sibling first ("source": "+ tr.subtext"). baseFields read values from the item element itself, and absoluteUrls resolves href, src and similar attributes. Missing values are omitted (or replaced by default), and items where nothing matched are skipped.

A schema can generate the equivalent typed DTO, which is a convenient way to move from a schema you prototyped (or one an LLM wrote) to reviewed, typed code:

file_put_contents('src/Quote.php', $schema->toPhpClass('App\\Quote'));

RegexExtractor finds well-known patterns in a page without any selector. It ports Crawl4AI’s pattern library: EMAIL, PHONE_INTL, PHONE_US, URL, IPV4, IPV6, UUID, CURRENCY, PERCENTAGE, NUMBER, DATE_ISO, DATE_US, TIME_24H, POSTAL_US, POSTAL_UK, HTML_COLOR_HEX, TWITTER_HANDLE, HASHTAG, MAC_ADDR, IBAN, CREDIT_CARD and ALL. Combine them with | and add your own named patterns:

regex.php
use Pam\Crawl\Crawl;
use Pam\Crawl\Extract\Input;
use Pam\Crawl\Extract\RegexExtractor;
$extractor = new RegexExtractor(
RegexExtractor::EMAIL | RegexExtractor::URL | RegexExtractor::DATE_ISO,
custom: ['php_version' => 'PHP \d+\.\d+'],
input: Input::Html,
);
foreach ($extractor->extract(Crawl::url('https://www.php.net/mailing-lists.php')->get()) as $match) {
echo $match['label'], ': ', $match['value'], "\n"; // also: url, span
}

Patterns are case-insensitive, like in Crawl4AI. The input option selects which representation of the page is searched: Input::FitHtml (the default, main content only), Input::Html, Input::CleanedHtml, Input::Markdown, Input::FitMarkdown or Input::Text.

CosineExtraction ports Crawl4AI’s CosineStrategy: the content is split into chunks, each chunk is embedded, chunks are grouped by hierarchical clustering, and each cluster is tagged with its most distinctive terms. It needs an embeddings provider (a local Ollama model works):

clusters.php
use Pam\Crawl\Crawl;
use Pam\Crawl\Extract\CosineExtraction;
use Pam\Crawl\Llm\Config;
use Pam\Crawl\Llm\Embeddings;
$extraction = new CosineExtraction(
new Embeddings(new Config('ollama/nomic-embed-text')),
semanticFilter: 'pricing',
maxDist: 0.2,
linkageMethod: 'ward',
);
$blocks = $extraction->extract(Crawl::url('https://example.com/pricing')->get());
// [['index' => 1, 'tags' => ['plan', 'seats', 'month'], 'content' => '...'], ...]

Linkage methods are ward, average, complete, single and weighted; the clustering matches SciPy’s linkage and fcluster(criterion="distance"). See LLM Features for embedding providers.

When you split content yourself (for embeddings or LLM calls), the Pam\Crawl\Chunk namespace has Crawl4AI’s chunking strategies: Identity, Regex, Sentence, TopicSegmentation, FixedLengthWord, SlidingWindow and OverlappingWindow. Each implements Chunker::chunk(string $text): list<string>. Merge::chunks() packs pieces into token-bounded windows with overlap:

use Pam\Crawl\Chunk\Merge;
use Pam\Crawl\Chunk\SlidingWindow;
$pieces = (new SlidingWindow(windowSize: 100, step: 50))->chunk($page->content->raw);
$windows = Merge::chunks($pieces, targetTokens: 2048, overlap: 200);

The Crawler Hub packages extraction logic as named, reusable crawlers. The built-in article crawler returns an article record (title, author and authors, published and modified in ISO 8601, description, image, site_name, language, keywords, the body as Markdown and its word_count) and reports which source each field came from (JSON-LD, Open Graph, meta tags or the page):

use Pam\Crawl\Hub\Hub;
$article = Hub::run('article', 'https://wordpress.org/news/');
echo $article['title'], ' — ', $article['published'], "\n";
print_r($article['sources']);

Register your own crawler with #[AsCrawler] and the Hub\Crawler interface:

src/DocsCrawler.php
use Pam\Crawl\Crawl;
use Pam\Crawl\Hub\AsCrawler;
use Pam\Crawl\Hub\Crawler;
#[AsCrawler('docs', description: 'Docs page as Markdown')]
final class DocsCrawler implements Crawler
{
public function run(string $url, array $options = []): array
{
return ['markdown' => Crawl::url($url)->get()->content->raw];
}
}

Once the class is loaded, Hub::names() lists it next to the built-ins and Hub::run('docs', $url) runs it. Hub::register(DocsCrawler::class) registers a class explicitly.


This product includes software developed by UncleCode (https://x.com/unclecode) as part of the Crawl4AI project (https://github.com/unclecode/crawl4ai).