PHP Web Scraping Tutorial: Working Code on PHP 8.5
A PHP web scraping tutorial with runnable code: curl and DOMXPath, Symfony DomCrawler, polite crawling, concurrency, and a browser render on PHP 8.5.

On this page
Most PHP web scraping tutorials still open with Goutte. The library was archived on April 1, 2023 and its repository has not been pushed since; building on it in 2026 means starting from a dead branch. The current stack is smaller than the tutorials suggest: two extensions that ship with PHP, plus one Composer package when the selectors get long.
Every program below ran today on PHP 8.5.8 against quotes.toscrape.com, a sandbox built for this, and I kept the timings: 1.1s for the first page, 20.6s for a polite ten-page crawl, 1.3s for the same ten pages concurrently, and 3.3 to 5.3s for the one page that needs a real browser. You get five runnable programs, the exact output each one printed, and the three traps I hit on the way.
What you need
- PHP 8.4 or newer (tested on 8.5.8). Symfony DomCrawler 8.1 requires PHP >= 8.4.1; if you are on 8.2 or 8.3, pin
symfony/dom-crawler:^7.4, which needs PHP >= 8.2 and the same API. The Step 1 code runs on any PHP 8.x with the standard extensions: curl, dom, mbstring. - Composer 2.11.1 for Steps 2 onward. I ran PHP from a static build (static-php.dev, single binary, no root install); a distro PHP with the standard extensions behaves the same.
- A sandbox: quotes.toscrape.com. Ten quotes per page, pagination, a JavaScript variant at
/js/, and a robots.txt that allows everything.
Step 1: The PHP web scraping baseline with curl and DOMXPath
Fetch with ext-curl, parse with DOMDocument and DOMXPath. No Composer, no dependencies beyond what every PHP install already has:
<?php
$url = 'https://quotes.toscrape.com/';
$start = microtime(true);
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 20,
CURLOPT_USERAGENT => 'php-scrape-demo/0.1 (tutorial example)',
]);
$html = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();
$xp = new DOMXPath($dom);
$quotes = $xp->query('//div[@class="quote"]');
$first = $quotes->item(0);
printf("status: %d\n", $status);
printf("bytes: %s\n", number_format(strlen($html)));
printf("quotes on page: %d\n", $quotes->length);
printf("first quote: %s\n", $xp->query('./span[@class="text"]', $first)->item(0)->textContent);
printf("author: %s\n", $xp->query('.//small[@class="author"]', $first)->item(0)->textContent);
printf("total: %.0fms\n", (microtime(true) - $start) * 1000);
Output from today’s run:
status: 200
bytes: 11,064
quotes on page: 10
first quote: “The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”
author: Albert Einstein
total: 1093ms
Three traps live in these 28 lines.
First, PHP 8.5 deprecates curl_close(). Old tutorials call it, and on 8.5 you get Deprecated: Function curl_close() is deprecated since 8.5, as it has no effect since PHP 8.0. It has done nothing for five years; delete the line.
Second, XPath axes are strict. My first draft used ./small[@class="author"] and got null back with a warning about reading a property on null, because the <small class="author"> sits inside an intermediate <span>, not directly under the quote <div>. The descendant axis .//small[...] finds it. A dot-slash that matches nothing fails silently, so when a query returns nothing, suspect the axis before the data.
Third, loadHTML recovers from broken markup without raising an error. I fed it <div><p>unclosed <p>tags and a stray &foo; entity; both parsed “fine”. That tolerance means a typo in your selector and a mangled page look identical: zero nodes, no exception. The libxml_use_internal_errors(true) / libxml_clear_errors() pair is the standard incantation; when a query comes back empty, dump $dom->saveHTML() and look at what PHP actually built. DOMDocument is PHP’s wrapper around the same DOM tree browsers expose, just without their forgiving error messages. (More on that tree: /glossary/dom.)
Step 2: Same page, Symfony DomCrawler
DOMXPath works. It also gets verbose fast: nested queries, manual node walking, quoted attribute syntax everywhere. DomCrawler wraps the same underlying libxml document with CSS selectors and an iterator API:
composer require symfony/dom-crawler symfony/css-selector
<?php
require __DIR__ . '/vendor/autoload.php';
use Symfony\Component\DomCrawler\Crawler;
$start = microtime(true);
$html = file_get_contents('https://quotes.toscrape.com/');
$crawler = new Crawler($html, 'https://quotes.toscrape.com/');
printf("quotes on page: %d\n", $crawler->filter('div.quote')->count());
$first = $crawler->filter('div.quote')->first();
printf("first quote: %s\n", $first->filter('span.text')->text());
printf("author: %s\n", $first->filter('small.author')->text());
$all = $crawler->filter('div.quote')->each(
fn (Crawler $q) => [
'text' => $q->filter('span.text')->text(),
'author' => $q->filter('small.author')->text(),
]
);
printf("extracted: %d pairs\n", count($all));
printf("total: %.0fms\n", (microtime(true) - $start) * 1000);
quotes on page: 10
first quote: “The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”
author: Albert Einstein
extracted: 10 pairs
total: 1332ms
The each() call is the payoff: one closure per node, typed objects back, no manual DOMNodeList walking. Under the hood, filter('div.quote') converts your CSS to XPath and queries the same DOM tree as Step 1, so results match exactly.
My rule: DOMXPath for a one-page script, DomCrawler the day the selectors get long enough to want CSS or a second person will read the code. If your project already ships Guzzle (8.3.1 is current), Guzzle replaces the fetch half cleanly and DomCrawler still handles the parse; they compose without ceremony.
Step 3: Crawl the pagination, politely
One page is a fetch. A crawl is a loop with a pause in it:
<?php
require __DIR__ . '/vendor/autoload.php';
use Symfony\Component\DomCrawler\Crawler;
$base = 'https://quotes.toscrape.com/';
$url = $base;
$pages = 0;
$quotes = [];
while ($url !== null && $pages < 10) {
$html = file_get_contents($url);
if ($html === false) {
fwrite(STDERR, "fetch failed: $url\n");
break;
}
$crawler = new Crawler($html, $url);
foreach ($crawler->filter('div.quote') as $node) {
$q = new Crawler($node, $url);
$quotes[] = [
'text' => $q->filter('span.text')->text(),
'author' => $q->filter('small.author')->text(),
'tags' => $q->filter('a.tag')->each(fn (Crawler $t) => $t->text()),
];
}
$pages++;
$next = $crawler->filter('li.next > a');
$url = $next->count() ? $base . ltrim($next->attr('href'), '/') : null;
if ($url !== null) {
sleep(1);
}
}
printf("pages: %d quotes: %d\n", $pages, count($quotes));
$authors = array_count_values(array_column($quotes, 'author'));
arsort($authors);
printf("top author: %s (%d quotes)\n", array_key_first($authors), current($authors));
printf("tags on quote 1: %s\n", implode(', ', $quotes[0]['tags']));
pages: 10 quotes: 100
top author: Albert Einstein (10 quotes)
tags on quote 1: change, deep-thoughts, thinking, world
Ten pages took 20.6s of wall clock. PHP itself was on the CPU for 0.37s of that, under two percent; the rest was sleep(1) and network waits. That is what a polite crawl looks like in a timeline. The li.next > a selector drives the loop, so it stops exactly where the site stops paginating.
Before you point this pattern at a site you don’t run: check robots.txt, keep the pause, and read /glossary/rate-limiting for what 429s look like when you don’t. The sleep(1) is not decoration; the whole point of a crawler is being welcome back tomorrow.
Step 4: Ten pages, concurrently
When the target tolerates it, Symfony’s HttpClient multiplexes requests instead of waiting on each in turn:
<?php
require __DIR__ . '/vendor/autoload.php';
use Symfony\Component\HttpClient\HttpClient;
$client = HttpClient::create(['timeout' => 20]);
$start = microtime(true);
$responses = [];
foreach (range(1, 10) as $p) {
$responses[] = $client->request('GET', "https://quotes.toscrape.com/page/$p/");
}
$ok = 0;
foreach ($client->stream($responses) as $response => $chunk) {
if ($chunk->isLast()) {
$ok++;
}
}
printf("fetched %d pages concurrently in %.2fs\n", $ok, microtime(true) - $start);
fetched 10 pages concurrently in 1.30s
The same ten pages in sequence, at this site’s measured ~1.1s per fetch, cost about eleven seconds. Concurrently: 1.30s. No threads, no async extensions; HttpClient interleaves the requests on PHP’s internal fibers and hands you chunks as they land.
The caveat is the point: concurrency multiplies your request rate by ten, which is exactly why it gets scrapers banned. On infrastructure you own, go wide. On someone else’s site, cap per-host concurrency low and keep the politeness pause in spirit even when the code is parallel. quotes.toscrape.com exists to absorb this; most sites don’t.
Step 5: The JavaScript wall, and the render step that clears it
quotes.toscrape.com has a JavaScript twin at /js/, and a static fetch gets nothing from it. Measured: 5,808 bytes, two <script> tags, and zero div.quote elements in the HTML. The quotes arrive via an XHR after page load, so no selector skill fixes this in PHP. The data is not in the response.
The fix is to drive a real browser and read the DOM after it settles. chrome-php/chrome (v1.16.1) talks the DevTools protocol straight to a Chrome binary, no chromedriver needed:
composer require chrome-php/chrome
<?php
require __DIR__ . '/vendor/autoload.php';
use HeadlessChromium\BrowserFactory;
$factory = new BrowserFactory(getenv('CHROME_BIN'));
$browser = $factory->createBrowser(['headless' => true, 'noSandbox' => true]);
$start = microtime(true);
$page = $browser->createPage();
$page->navigate('https://quotes.toscrape.com/js/')->waitForNavigation();
usleep(800_000); // let the XHR land
$count = $page->evaluate('document.querySelectorAll("div.quote").length')->getReturnValue();
printf("quotes after render: %d\n", $count);
printf("render total: %.2fs\n", microtime(true) - $start);
$browser->close();
quotes after render: 10
render total: 5.27s
Ten quotes from the page Step 1’s twin could not see. The timer starts after the browser process spawns and covers page creation, navigation, render, and the 0.8s settle; across runs this measured 3.3s and 5.3s, so quote it as “seconds”, not as one number. I pointed CHROME_BIN at Chrome for Testing 156.0.8078.4; any Chrome or Chromium binary works the same way. The Symfony-flavored alternative is Panther (v2.4.0), which drives browsers through the W3C WebDriver standard and needs a chromedriver matched to your browser version. Where JS rendering fits in the bigger picture: /glossary/javascript-rendering.
Escalation logic matters more than the library choice. Static first, render only when the static HTML demonstrably lacks the data. A render costs seconds and a browser process; a static fetch costs 1.1s and nothing.
When the plumbing is not your product. Everything above is fetch-parse-render scaffolding you maintain by hand. A local scraper CLI collapses the same three stages into one command per step; I use Magpie (Go, AGPL-3.0-or-later or commercial) for exactly this: static fetch first, escalation to a real browser when the page needs JS, clean markdown out. Worth a look when you would rather maintain selectors than sockets.
What breaks outside the sandbox
Requests without a User-Agent get refused. PHP’s curl sends an empty UA by default. I fetched the same Wikipedia page twice in the same minute: empty UA returned 403, php-scrape-demo/0.1 (tutorial) returned 200. Set CURLOPT_USERAGENT on every handle, and use a UA that names the scraper honestly where the site’s terms allow scraping at all.
Header fixes stop at TLS. Some sites fingerprint the TLS handshake itself and block your client no matter what headers it sends. No PHP function fixes that; your options are a proxy with client-hello impersonation or a real browser, which is a different budget line.
Quiet parse failures compound. Step 1’s third trap scales: a site redesign that mangles one div turns into a silent stream of empty records, not an error you can alert on. Log record counts per run. A page that produced 100 rows yesterday and 0 today should wake someone up.
FAQ
Is PHP good for web scraping?
For HTML that arrives in the initial response, yes: the extensions are fast, deployment is boring, and curl handles cookies and redirects. PHP has no native answer for JavaScript rendering or TLS-level blocks, so either drive a browser from PHP (Step 5) or use a stack that already runs one; the same walkthrough exists in Go.
What replaced Goutte?
Nothing one-for-one, because Goutte was a thin wrapper. Its README points at the Symfony components it wrapped: BrowserKit, HttpClient, CssSelector. Guzzle 8.x covers the fetch half, DomCrawler the parse half. Porting old Goutte code is mechanical: the filter() calls carry over almost unchanged.
How do I scrape JavaScript-rendered pages with PHP?
Drive a browser. chrome-php/chrome speaks the DevTools protocol to any Chrome binary; my Step 5 run pulled 10 quotes in 3.3 to 5.3s. Symfony Panther v2.4 does it through the W3C WebDriver standard and needs a matching chromedriver. Both cost seconds per page, so escalate only when the static HTML lacks the data.
Which PHP scraping library should I start with?
The two built-in extensions. If DOMXPath and curl solve the page, you are done in 30 lines with no Composer dependencies. Add DomCrawler when selectors get long enough to want CSS or a second maintainer. Frameworks and browser orchestration are the last stop, not the first.
Is PHP web scraping legal?
The language is irrelevant; the data, the site’s terms, and your jurisdiction decide. robots.txt, rate limits, and copyright apply the same to a PHP script and a browser. Scraping public data can still breach terms of service, so read them before the first request, not after the first letter. This is context, not legal advice.
Where to go from here
Write PHP when the scraping logic is your product: custom logins, domain rules, an output shape nobody else needs. When the plumbing is the product and you keep rebuilding fetch-parse-render for every job, that is the signal to pick up a dedicated tool instead of another script.
The same walkthrough exists for two sibling stacks: Go, standard library to headless browser, and Python with BeautifulSoup. If you want a first run against real code, take Step 1 as-is, point $url at a page you are allowed to scrape, and time it. The 1.1s number will not match. The shape of the program will.


