PHP Tutorials
•
Nov 30, 2026

Web Scraping PHP vs Python: Key Differences and Modern PHP Examples

Python still leads classic scraping, but LLM extraction changes the math. PHP is the solution.

Matt Payne
Matt Payne

Web scraping PHP vs Python used to have a simple answer: Python, because its libraries were better. The short answer today depends on where the data goes. Use Python when scraping is the product. Use PHP when scraping feeds a PHP app you already run.

What changed is extraction. When a large language model (LLM) reads the page and fills in a schema, the hard part stops being CSS selectors. It becomes an API call plus checks on what comes back, and PHP makes API calls as well as Python does.

We build extraction systems for a living, so we tested this instead of arguing it. Below you will find the key differences, a timing test of the same scrape in both languages, and six PHP scraping examples that ran on PHP 8.4. We also cover where Python still wins, because it does.

Key Takeaways

  • Scraping waits on the network. In our test, PHP and Python finished the same 50-page scrape within a second of each other.
  • Fetching five pages at once cut the time by about 3.5 times in both languages, so concurrency matters far more than language.
  • PHP 8.4 has a built-in HTML5 parser with CSS selectors, so basic scraping needs no extra parser.
  • With LLM extraction, you define a schema instead of selectors. PHP handles that through Prism, Firecrawl's SDK or a REST call.
  • Python still leads on local AI crawlers, browser agents, large crawling frameworks and data analysis.

Web Scraping PHP vs Python: The Key Differences

Both languages can fetch a page, parse it and save the result. The differences show up in the libraries around that core, in how each runs many requests at once, and in where the scraper lives once it ships.

  

PHP vs Python

  

Web scraping in PHP and Python, side by side

  
                                                                    
DifferencePHPPython
HTTP and parsingGuzzle; PHP 8.4's built-in Dom\HTMLDocument with CSS selectorsrequests or httpx; lxml, parsel
Many pages at onceGuzzle Pool, curl_multi, Amp or ReactPHP (built on Fibers)asyncio with httpx or aiohttp; Scrapy
JavaScript pagesSymfony Panther, chrome-php, Browsershot (needs Node)Playwright, Selenium
AI and LLM toolingPrism, the official Anthropic SDK, openai-php/client, Firecrawl's PHP SDKCrawl4AI, ScrapeGraphAI, browser-use, Firecrawl
Crawling frameworksspatie/crawler; roach-php (last release Mar 2025)Scrapy
After the scrapeArrays, Eloquent models, your app's databasepandas, notebooks, data pipelines
Where it runsInside your PHP app, on its queueUsually a separate service or worker
  
  

Library versions and activity checked on Packagist and GitHub, November 5, 2026.

‍

The ecosystem gap is real. Python has Scrapy for large crawls and a wave of AI-first crawlers. PHP has fewer scraping tools, but the ones that matter are mature. Guzzle, PHP's standard HTTP client, has passed 1.1 billion installs on Packagist.

Where the scraper runs is easy to overlook. A PHP scraper runs inside your app, uses its queue and writes to its database. A Python scraper next to a PHP app is a second service to deploy, monitor and keep in sync.

Speed: We Timed the Same Scrape in Both

Speed comes up in every PHP vs Python debate, so we measured it. We scraped all 50 catalog pages of Books to Scrape, a public practice site, in both languages. That is 1,000 books. We ran it one page at a time, then five pages at once, three rounds each.

  

Our timing test

  

The same scrape in both languages

  
                                            
50 pages, 1,000 booksPHP 8.4Python 3.9
One page at a time12.1 s12.9 s
Five pages at once3.4 s3.7 s
Time spent parsing HTMLunder 0.1 sabout 0.1 s
  
  

Middle of 3 runs on November 5, 2026, against books.toscrape.com from one machine on a home connection. PHP: Guzzle + Dom\HTMLDocument. Python: requests or httpx + lxml.

‍

PHP came in slightly ahead, but less than a second apart is too small to matter. Parsing took about a tenth of a second out of 3 to 13 seconds in total. The rest was waiting on the network. The big change came from fetching five pages at once, which cut the time by about 3.5 times in both languages.

Treat these as one test, not a benchmark. It ran on one machine and a home connection against one site. Still, the lesson holds for most scraping jobs: pick the language for its tools and where it runs, then make it concurrent.

What LLMs Changed About Web Scraping

A classic scraper maps each field to a selector, such as the price living in the element with class price_color. That works until the site changes its markup. Then the selector returns nothing, or the wrong thing, and someone has to fix it by hand for every site you scrape.

LLM extraction flips that. You clean the page down to text, describe the fields you want in a schema, and the model fills it in. The schema does not care where the price sits in the HTML, so the same schema works across many sites and survives most redesigns.

Fetching stays the same. The fragile step moves from selectors to a schema you validate.
Fetching stays the same. The fragile step moves from selectors to a schema you validate.

The work does not disappear. It moves to four places: fetching the page, cleaning it to text, defining the schema, and validating the output. Each page now costs tokens and adds a second or more of latency. Models also get fields wrong now and then, so every row needs a check before it reaches your database.

This is why the language question matters less than it did. Fetching is the same in both. Cleaning is a few lines. The schema and the model call are an HTTP request, and every major model has an official or well-kept PHP client.

The Modern Python Scraping Stack

Python is where most new AI scraping tools ship first. These are the ones worth knowing, with GitHub stars as of November 5, 2026.

  • Crawl4AI (86.9K stars, Apache-2.0) crawls sites and turns pages into clean markdown ready for an LLM. It includes extraction strategies that use either a model or CSS rules.
  • browser-use (120.1K stars, MIT) lets an AI agent drive a real browser: click, type and move through pages to finish a task.
  • ScrapeGraphAI (32.5K stars, MIT) builds scraping pipelines from a prompt, so you describe what you want and it plans the steps.
  • Firecrawl (198.8K stars, AGPL-3.0) turns websites into markdown or structured data through an API, and it can be self-hosted.
  • Scrapy (65.2K stars, BSD-3-Clause) is still the standard framework for large crawls, with scheduling, retries and pipelines built in.

Playwright for Python covers browser automation for JavaScript-heavy sites. For analysis after the scrape, pandas and notebooks are still Python's strongest pull.

Web Scraping Examples in PHP

These six examples go from plain parsing to full AI extraction. Each one ran on PHP 8.4.23 on November 5, 2026. Examples 1 to 3 scraped real practice pages. Examples 4 to 6 sent real requests to a local stand-in for each API, because the calls need paid keys.

Example 1: Fetch and Parse Pages With PHP 8.4

PHP 8.4 added Dom\HTMLDocument, a built-in HTML5 parser with querySelector and querySelectorAll. You no longer need a third-party parser or XPath for basic web scraping with PHP. Install Guzzle with composer require guzzlehttp/guzzle, then run this. It ran on Guzzle 7.16 and 8.3:

<?php
require __DIR__ . "/vendor/autoload.php";
 
use GuzzleHttp\Client;
 
$http = new Client([
    "base_uri" => "https://books.toscrape.com/",
    "timeout"  => 20,
    "headers"  => ["User-Agent" => "ExampleBot/1.0 (+https://example.com/bot)"],
]);
 
$html = (string) $http->get("catalogue/page-1.html")->getBody();
$doc  = Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR);
 
$books = [];
foreach ($doc->querySelectorAll("article.product_pod") as $card) {
    $link = $card->querySelector("h3 a");
    $books[] = [
        "title" => $link?->getAttribute("title"),
        "price" => trim($card->querySelector(".price_color")?->textContent ?? ""),
        "url"   => $link?->getAttribute("href"),
    ];
}
 
echo count($books), " books\n";
print_r($books[0]);

This printed 20 books, starting with A Light in the Attic at £51.77. The weak spot is the selectors. If the site renames product_pod, this returns nothing, which is the problem example 4 solves.

Example 2: Scrape Many Pages at Once With a Guzzle Pool

Concurrency is where the time goes, as the speed test showed. A Guzzle Pool sends several requests at once and hands each response to a callback. Keep concurrency low on sites you do not own, since five parallel requests is already a lot for a small site.

<?php
require __DIR__ . "/vendor/autoload.php";
 
use GuzzleHttp\Client;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Request;
 
$http = new Client([
    "base_uri" => "https://books.toscrape.com/",
    "timeout"  => 20,
    "headers"  => ["User-Agent" => "ExampleBot/1.0 (+https://example.com/bot)"],
]);
 
$urls = [];
for ($page = 1; $page <= 10; $page++) {
    $urls[] = "catalogue/page-$page.html";
}
 
$requests = function (array $urls) {
    foreach ($urls as $url) {
        yield new Request("GET", $url);
    }
};
 
$pages = [];
$pool = new Pool($http, $requests($urls), [
    "concurrency" => 5,
    "fulfilled"   => function ($response, $i) use (&$pages) {
        $pages[$i] = (string) $response->getBody();
    },
    "rejected"    => function ($reason, $i) {
        error_log("Request $i failed: " . $reason->getMessage());
    },
]);
$pool->promise()->wait();
 
$count = 0;
foreach ($pages as $html) {
    $doc = Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR);
    $count += count($doc->querySelectorAll("article.product_pod"));
}
echo count($pages), " pages, $count books\n";

Ten pages and 200 books came back in about 1.6 seconds. Failed requests go to the rejected callback, so one bad page does not stop the run.

Example 3: Scrape JavaScript Pages With Symfony Panther

Some pages build their content in the browser, so the raw HTML is empty. Symfony Panther drives a real Chrome or Firefox and gives you the rendered page. Install it with composer require symfony/panther, then add chromedriver with the bdi driver installer: composer require --dev dbrekelmans/bdi, then vendor/bin/bdi detect drivers. Panther finds the driver in the drivers folder on its own.

<?php
require __DIR__ . "/vendor/autoload.php";
 
use Symfony\Component\Panther\Client;
 
$client = Client::createChromeClient();
$client->request("GET", "https://quotes.toscrape.com/js/");
$crawler = $client->waitFor(".quote");
 
$quotes = $crawler->filter(".quote")->each(fn ($node) => [
    "text"   => $node->filter(".text")->text(),
    "author" => $node->filter(".author")->text(),
]);
$client->quit();
 
echo count($quotes), " quotes\n";
print_r($quotes[0]);

The raw HTML of this page has zero quotes in it. Panther waited for the JavaScript to run and returned all 10. A real browser is slow and memory hungry, so use it only for pages that need it.

Example 4: Extract Fields With Claude Through Prism

This is the LLM approach in PHP. Prism is a Laravel package that talks to Claude, OpenAI and other models with one API, and it supports structured output against a schema. Install it with composer require prism-php/prism and set ANTHROPIC_API_KEY in .env. The example is an Artisan command:

<?php
 
namespace App\Console\Commands;
 
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Prism\Prism\Facades\Prism;
use Prism\Prism\Enums\Provider;
use Prism\Prism\Schema\ObjectSchema;
use Prism\Prism\Schema\StringSchema;
use Prism\Prism\Schema\NumberSchema;
use Prism\Prism\Schema\BooleanSchema;
 
class ExtractProduct extends Command
{
    protected $signature = 'scrape:product {url}';
 
    public function handle(): void
    {
        $html = Http::withUserAgent("ExampleBot/1.0 (+https://example.com/bot)")
            ->get($this->argument("url"))->throw()->body();
 
        // 1. Clean the page so the model sees content, not markup
        $doc = \Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR);
        foreach ($doc->querySelectorAll("script, style, noscript, svg") as $node) {
            $node->remove();
        }
        $text = preg_replace("/\s+/", " ", $doc->body?->textContent ?? "");
        $text = mb_substr($text, 0, 40000); // cap tokens per page
 
        // 2. Define what you want, not where it lives
        $schema = new ObjectSchema(
            name: "product",
            description: "Product details found on the page",
            properties: [
                new StringSchema("name", "Product name"),
                new NumberSchema("price", "Current price as a number, no currency symbol", nullable: true),
                new StringSchema("currency", "ISO 4217 code, e.g. USD"),
                new BooleanSchema("in_stock", "Whether the product can be bought now"),
            ],
            requiredFields: ["name", "price", "currency", "in_stock"],
        );
 
        // 3. Ask the model
        $response = Prism::structured()
            ->using(Provider::Anthropic, "claude-sonnet-5-5")
            ->withSchema($schema)
            ->withMaxTokens(1024)
            ->withPrompt("Extract the product from this page. Use null for a price you cannot find.\n\n" . $text)
            ->asStructured();
 
        $product = $response->structured;
 
        // 4. Check it before you save it
        if ($product["price"] === null || $product["price"] <= 0 || strlen($product["currency"]) !== 3) {
            throw new \RuntimeException("Extraction failed checks for " . $this->argument("url"));
        }
        $product["source_url"] = $this->argument("url");
        print_r($product);
    }
}

Run it with php artisan scrape:product and a product URL. Notice there is not a single product selector. The code strips scripts and styles, caps the text at 40,000 characters to control tokens, and describes the four fields it wants.

Three details came from testing. With Claude, Prism sent a 64,000-token output limit by default, so withMaxTokens(1024) keeps each page cheap. The price is nullable, because a prompt that asks for null fails if the schema forbids it. And the check step rejects bad rows before they are saved, with the source URL attached for tracing.

On Claude Sonnet 4.5 and later, Prism uses Claude's native structured output, so the reply must match your schema. That guarantees the shape, not the facts. A wrong price in the right format still needs your check.

Example 5: Scrape Pages Through Firecrawl's PHP SDK

If you would rather not run browsers or proxies, a managed API does the fetching and the extraction. Firecrawl ships an official PHP SDK. Install it with composer require firecrawl/firecrawl-sdk and set FIRECRAWL_API_KEY.

<?php
require __DIR__ . "/vendor/autoload.php";
 
use Firecrawl\Client\FirecrawlClient;
use Firecrawl\Models\ScrapeOptions;
use Firecrawl\Models\JsonFormat;
 
$client = FirecrawlClient::fromEnv(); // reads FIRECRAWL_API_KEY
 
$doc = $client->scrape("https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html", ScrapeOptions::with(
    formats: [JsonFormat::with(
        prompt: "Extract the book title and price",
        schema: [
            "type" => "object",
            "properties" => [
                "name"  => ["type" => "string"],
                "price" => ["type" => "number"],
            ],
            "required" => ["name", "price"],
        ],
    )],
));
 
$data = $doc->getJson();
var_dump($data);

Rendering, proxies and extraction happen on Firecrawl's side, and PHP just makes the call. The same client also has crawl() for whole sites, map() to list a site's URLs, and agent() for open-ended research tasks. It includes a Laravel service provider and facade.

Example 6: Scrape Product Data With Pumice's Smart Scraper

Product pages are their own problem. Each store lays out titles, prices, materials and dimensions differently. Pumice, our product data platform, has a Smart Scraper that takes a plain-language prompt and a URL and returns structured fields. It is a REST API, so it works from PHP with Guzzle:

<?php
require __DIR__ . "/vendor/autoload.php";
 
use GuzzleHttp\Client;
 
$pumice = new Client([
    "base_uri" => "https://app.pumice.ai/api/",
    "timeout"  => 120,
    "headers"  => ["x-api-key" => getenv("PUMICE_API_KEY")],
]);
 
$res = $pumice->post("scraper/smart-scrape", ["json" => [
    "source_url" => "https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html",
    "prompt"     => "Return the product title, price, stock status and product description.",
]]);
 
$result = json_decode((string) $res->getBody(), true);
print_r($result);

On a 429 or 5xx response, wait and retry. To find the right product page first, call the universal scraper endpoint with a search query. We use the same research step to pull Amazon product data with AI agents, and the fields it returns feed product attribute enrichment, where missing attributes get filled in against your catalog rules.

Where Python Still Wins

PHP covers the common jobs. Python still leads in four places, and pretending otherwise would cost you time.

  • Local AI crawlers and browser agents. Crawl4AI and browser-use have no PHP equal. If you want an agent that explores a site on its own, or a crawler that runs a local model, use Python.
  • Large crawls. Scrapy handles scheduling, retries, throttling and pipelines for millions of pages. PHP has spatie/crawler, and roach-php, a Scrapy-style framework, has not released since March 2025 and supports PHP only up to 8.4.
  • Hard targets. Python has more low-level HTTP tooling for sites that inspect how a client connects. Use it only where a site's terms allow automated access.
  • Analysis. If the scraped data goes into a notebook, pandas and Python's data tools win.

You do not have to choose one. A common setup runs a Python worker for collection and keeps the PHP app for everything else. The worker pushes results onto a queue or into the database, and the app reads them like any other data.

Which Should You Use?

  
    The short answer    

Should you use PHP or Python for web scraping?

    

Use PHP when the scraped data feeds an existing PHP or Laravel app, the sites are known, and volume is moderate; let an LLM or a scraping API handle extraction. Use Python when scraping is the product: millions of pages, hard anti-bot targets, or crawlers and browser agents that explore on their own. For both, run a Python worker for collection and keep the PHP app, with a queue in between.

  

‍

Choose PHP when the data feeds an app you already run in PHP or Laravel, you know which sites you need, and volume is moderate. Use an LLM or a scraping API for extraction, and the selector maintenance mostly goes away.

Choose Python when scraping is the product: millions of pages, sites that fight automation, or crawlers and agents that decide where to go next. Its ecosystem is built for that work.

Seen that way, web scraping PHP vs Python is less a choice of language than a choice of where the scraper lives. Choose both when collection is large but the app is PHP. Put a queue between them, and each side does what it does best.

Guardrails for LLM Scraping

An LLM makes scraping easier to start, which makes these rules more important. They apply in both languages.

  • Check robots.txt and the terms of service. If a site forbids automated access, use its API or ask for a data feed.
  • Slow down and identify yourself. Keep concurrency low, add delays, and send a User-Agent with a contact URL, as the examples do.
  • Leave personal data alone. Scraping names, emails or profiles brings privacy law into play. Collect only what the job needs.
  • Validate every row. Check types and ranges against the schema, and send failures to a review queue instead of the database.
  • Keep the source URL. Store it with every row, so any value can be traced and rechecked.
  • Watch token cost. Cap the text per page and the output tokens, and log usage per run so a bad loop cannot run up a bill.

Conclusion

Web scraping PHP vs Python is no longer a contest of parsers. Fetching runs at the same speed in both, and LLM extraction turns the hardest part into a schema and a model call. Python remains the choice when scraping is the product. PHP is a fair choice when the data feeds a PHP app, and the six examples above are a working start.

‍

Need Extraction That Holds Up Across Thousands of Pages?

We build LLM extraction pipelines in the stack you already run, PHP or Python, with the schema, checks and retries that keep bad rows out of your database.

  • Schemas built around the fields your business uses

  • Validation, source URLs and human review on every row that matters

  • Cost limits per page, so token spend stays predictable

  • For product catalogs: Pumice's Smart Scraper does this out of the box

  
    Custom extraction pipelines    

Need Extraction That Holds Up Across Thousands of Pages?

    

We build LLM extraction pipelines in the stack you already run, PHP or Python, with the schema, checks and retries that keep bad rows out of your database.

                                                    
Schemas built around the fields your business uses
Validation, source URLs and human review on every row that matters
Cost limits per page, so token spend stays predictable
For product catalogs: Pumice's Smart Scraper does this out of the box
    Talk to us about your pipeline →  

‍

Frequently Asked Questions

Which language is best for web scraping?

In web scraping PHP vs Python, Python is the best choice when scraping is the main job, thanks to Scrapy, Playwright and AI crawlers like Crawl4AI. PHP is a good choice when the data feeds a PHP app, since it can fetch, parse, render JavaScript and call LLMs. In our test the two ran at nearly the same speed.

Is PHP a dying language?

No. PHP still ships yearly releases, and PHP 8.4 added a built-in HTML5 parser with CSS selectors. Its package registry is busy too: Guzzle alone draws over 31 million installs a month on Packagist.

Is PHP outdated in 2026?

Not for web scraping. Modern PHP has a native HTML5 parser, concurrent HTTP through Guzzle, real browser automation through Panther, and clients for Claude, OpenAI and Firecrawl. What it lacks is Python's newest AI crawler and browser agent projects.

Can PHP scrape JavaScript-heavy sites?

Yes. Symfony Panther drives a real Chrome or Firefox and returns the page after its JavaScript runs, and chrome-php does the same through the Chrome DevTools Protocol. A managed API like Firecrawl renders pages for you as well.

Can I use an LLM to scrape a website in PHP?

Yes. Fetch the page, strip it to text, and send it to a model with a schema. Prism does this for Claude and OpenAI in Laravel, and Firecrawl's PHP SDK accepts a prompt and schema in one call. Validate the output before you save it.

‍

Instant Access To PHP Case Studies

Read real use cases and whitepapers using PHP