Skip to content

Markdown & Content

Most crawls end in one of two places: a Markdown document an LLM can read, or data your application stores. This page covers both. You will learn how PAM Crawl builds Markdown, how to narrow it to the content you care about, and how to read everything else a page carries: links, images, tables, metadata, JSON-LD, feeds, JSON bodies and PDFs.

Every page exposes two Markdown documents:

use Pam\Crawl\Crawl;
$page = Crawl::url('https://en.wikipedia.org/wiki/Web_crawler')->get();
$page->markdown->raw; // the whole page as GitHub-flavored Markdown
$page->content->raw; // main content only, boilerplate removed

$page->markdown is the full page (Crawl4AI’s raw_markdown). $page->content runs the page through a main-content filter first (Crawl4AI’s fit_markdown): blocks are scored Readability-style, link-dense areas are penalized, and navigation, sidebars, share buttons, tables of contents and footers are stripped. For RAG and LLM prompts, $page->content is almost always what you want.

Both are Pam\Crawl\Markdown\Markdown objects with three strings, and the object casts to its raw string:

Property / method Description
raw The Markdown with inline links.
withCitations The same text with links replaced by numbered markers such as ⟨1⟩.
references The numbered reference list that goes with withCitations.
cited() withCitations followed by references.

Citations keep link-heavy text readable for a model while preserving every URL:

echo $page->markdown(citations: true);
// A web crawler is an Internet bot⟨1⟩ that systematically browses ...
//
// ⟨1⟩ https://en.wikipedia.org/wiki/Internet_bot: Internet bot

Pass focus to keep only the blocks relevant to a question. PAM Crawl scores the page’s blocks with BM25 (with stemming, and extra weight for headings, bold text and code) and drops the rest:

$page = Crawl::url('https://docs.python.org/3/library/asyncio-task.html')->get();
echo $page->markdown(focus: 'cancel a task with a timeout');

$page->markdown() also accepts any content filter. Three ship with the package:

Filter Description
Content\MainContentFilter The default for $page->content: picks the main content container and strips boilerplate.
Content\PruningFilter Crawl4AI’s pruning filter: removes low-scoring blocks by text density, link density and tag weight.
Content\Bm25Filter Keeps blocks that match a query. markdown(focus: ...) uses it with the default threshold.
use Pam\Crawl\Content\Bm25Filter;
use Pam\Crawl\Content\PruningFilter;
$pruned = $page->markdown(filter: new PruningFilter(threshold: 0.48));
$tight = $page->markdown(filter: new Bm25Filter('cancel a task with a timeout', threshold: 4.0));

PruningFilter accepts threshold (default 0.48), dynamic, minWords, preserveTags and preserveClasses. Bm25Filter accepts query (when omitted, the page’s title, first h1, meta keywords and description are used), threshold (default 1.0), stemming and keepHeadings. A fourth filter, Llm\LlmContentFilter, asks an LLM to clean the HTML; see LLM Features.

To use a filter for a whole crawl, set it on the crawler. It then drives both $page->markdown and $page->content:

$crawler = Crawl::urls($urls)->filter(new PruningFilter());

You can narrow the HTML before Markdown is generated. These options mirror Crawl4AI’s css_selector, target_elements, excluded_tags and excluded_selector:

docs-markdown.php
use Pam\Crawl\Crawl;
$page = Crawl::url('https://docs.example.com/guide/')
->target('main article') // Markdown from these elements only
->exclude('.edit-link, .toc') // drop these elements
->excludeTags('aside', 'form') // drop these tags
->withoutImages() // no images in the Markdown
->get();
Method Description
selector(string $css) Restrict everything (Markdown, links and media) to matching elements.
target(string ...$css) Build Markdown only from matching elements, but keep links and media from the whole page.
exclude(string $css) Remove matching elements. Can be called several times.
excludeTags(string ...$tags) Remove these tags.
wordThreshold(int $words) Minimum words for a text block to be kept (default 1).
keepForms() Keep forms, which are removed by default.
withoutImages() / withoutLinks() Leave images or links out of the Markdown.
onlyText() Flatten inline formatting to plain text.
keepAttributes(string ...$attributes) / keepDataAttributes() Attributes kept in $page->cleanedHtml.

Link and image filters change what $page->links and $page->images contain: excludeExternalLinks(), excludeInternalLinks(), excludeSocialLinks(), excludeDomains(string ...$domains), excludeExternalImages() and excludeAllImages().

Different URLs often need different rules. Use when() to apply content options per URL pattern in a single crawl; see per-URL rules.

$page->meta collects the <head>: title, description, keywords, author, canonical, lang, robots, image, favicon, published, modified, siteName and type, plus the og, twitter, feeds, alternates and all arrays.

$meta = $page->meta;
printf("%s (%s) canonical: %s\n", $meta->title, $meta->lang, $meta->canonical);
print_r($meta->og);

$page->links holds internal and external lists of Result\Link objects. Each link has a url, text, title, rel, the surrounding context text, an internal flag and a nofollow() helper.

printf("%d internal, %d external\n", count($page->links->internal), count($page->links->external));
foreach ($page->links->matching('*/wiki/Guido*') as $link) {
echo $link->text, ' -> ', $link->url, "\n";
}
$urls = $page->links->urls(internalOnly: true);

$page->images, $page->videos and $page->audios are lists of Result\Media objects with src, type, alt, description, width, height, format and a relevance score. Images are scored like Crawl4AI does (size, alt text, position on the page, format, srcset, <picture>), and images scoring 2 or less are dropped as decoration, so sorting by score puts the best candidates for a thumbnail first:

$images = $page->images;
usort($images, fn ($a, $b) => $b->score <=> $a->score);
echo $images[0]->src ?? 'no image';

$page->tables detects data tables (layout tables are skipped) and resolves rowspan and colspan. Each Result\Table has headers, rows, caption, summary and a score, and converts itself:

foreach ($page->tables as $table) {
echo $table->toMarkdown(), "\n";
file_put_contents('table.csv', $table->toCsv());
}

$page->jsonLd is the list of decoded JSON-LD nodes on the page:

foreach ($page->jsonLd as $node) {
echo $node['@type'] ?? '?', ': ', $node['name'] ?? '', "\n";
}

To map JSON-LD straight into a typed object, use the #[JsonLd] attribute from Extraction.

select() and first() run a CSS selector over the original document and return DOM elements:

foreach ($page->select('main h2') as $heading) {
echo trim($heading->textContent), "\n";
}

By default PAM Crawl accepts HTML, XHTML, XML, JSON and plain text. Feeds and JSON bodies get dedicated accessors, and their Markdown is generated from the parsed data:

feeds.php
use Pam\Crawl\Crawl;
$pages = Crawl::urls([
'https://wordpress.org/news/feed/',
'https://httpbin.org/json',
])
->anyContentType()
->header('Accept', 'application/json, application/rss+xml;q=0.9, */*;q=0.5')
->all();
foreach ($pages as $page) {
if ($page->feed !== null) {
foreach ($page->feed->items as $item) {
echo $item['date'], ' ', $item['title'], "\n"; // also: link, summary, id
}
} elseif (is_array($page->json)) {
echo $page->json['slideshow']['title'], "\n";
}
}

$page->feed is a Result\Feed (RSS or Atom) with title, link and items, or null. $page->json is the decoded body when the response is JSON.

Non-text responses are skipped unless you ask for them. downloads() streams them to a directory instead of keeping them in memory, and $page->pdf reads a downloaded PDF:

pdf.php
use Pam\Crawl\Crawl;
$page = Crawl::url('https://www.rfc-editor.org/rfc/rfc9309.pdf')
->downloads(sys_get_temp_dir().'/pdfs', maxBytes: 20 * 1024 * 1024)
->get();
if ($pdf = $page->pdf) {
print_r($pdf->info()); // title, author, pages, producer, created, pdf_version...
echo $pdf->markdown(); // the text as Markdown
print_r($pdf->links()); // URI links found in the document
}
echo $page->file; // where the PDF was saved

PdfDocument also offers text(), pages(), lazyPages(), batches(), images() and engine(). The built-in parser is used by default; when poppler’s pdftotext is installed it is used instead. PdfDocument::fromString($bytes) parses PDF bytes you already have.

Sites often serve the same content under several URLs: print views, tracking parameters, mirrored paths. dedupeContent() computes a 64-bit SimHash of each page’s main content and skips pages within a few bits of one already yielded:

$pages = Crawl::urls($urls)->dedupeContent(bits: 3)->all();

The hash is available as $page->simhash, and Text\SimHash::distance($a, $b) compares two of them. Memory cost is 8 bytes per unique page.

Export\Jsonl is a page hook: register it with onPage() and each page is written as one JSON line the moment it arrives, so nothing is buffered:

export.php
use Pam\Crawl\Crawl;
use Pam\Crawl\Export\Jsonl;
use Pam\Crawl\Page;
Crawl::site('https://docs.example.com/')
->limit(100)
->onPage(new Jsonl('docs.jsonl', fn (Page $page): array => [
'url' => $page->url,
'title' => $page->meta->title,
'markdown' => $page->content->raw,
]))
->each(fn () => null);

Without a mapping closure, each line is $page->toArray().

Export\Csv::write() writes any iterable of arrays or objects (such as extracted DTOs) and returns the number of rows. Nested arrays become JSON cells:

use Pam\Crawl\Export\Csv;
$rows = Csv::write('books.csv', $page->extractAll(Book::class));

Pam\Crawl\Stats is another hook. It counts pages, failures, cache hits and bytes, and tracks latency percentiles:

use Pam\Crawl\Stats;
$stats = new Stats();
Crawl::urls($urls)->onPage($stats)->each(fn () => null);
echo $stats; // 8 pages (7 ok, 1 failed, 0 cached) in 1.2s — 6.6 pages/s, p50 ..., p95 ...

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